From 2ab3498ab0a96efdd61930b21979aacc621cc2be Mon Sep 17 00:00:00 2001 From: David Anderson Date: Sun, 8 Mar 2015 12:37:10 -0700 Subject: [PATCH] Use upstream SourcePawn as a submodule. --- .gitmodules | 3 + AMBuildScript | 32 +- sourcepawn | 1 + sourcepawn/compiler/AMBuilder | 79 - sourcepawn/compiler/Makefile | 74 - sourcepawn/compiler/amx.h | 634 -- sourcepawn/compiler/amxdbg.h | 173 - sourcepawn/compiler/binreloc.c | 766 -- sourcepawn/compiler/binreloc.h | 80 - sourcepawn/compiler/getch.h | 15 - sourcepawn/compiler/libpawnc.cpp | 346 - sourcepawn/compiler/lstring.cpp | 124 - sourcepawn/compiler/lstring.h | 26 - sourcepawn/compiler/memfile.cpp | 116 - sourcepawn/compiler/memfile.h | 66 - sourcepawn/compiler/memory-buffer.h | 103 - sourcepawn/compiler/osdefs.h | 111 - sourcepawn/compiler/pawn.ico | Bin 8478 -> 0 bytes sourcepawn/compiler/pawncc.cpp | 43 - sourcepawn/compiler/sc.h | 1014 --- sourcepawn/compiler/sc1.cpp | 7955 ----------------- sourcepawn/compiler/sc2.cpp | 3274 ------- sourcepawn/compiler/sc3.cpp | 3219 ------- sourcepawn/compiler/sc4.cpp | 1519 ---- sourcepawn/compiler/sc5-in.scp | 272 - sourcepawn/compiler/sc5.cpp | 243 - sourcepawn/compiler/sc6.cpp | 1045 --- sourcepawn/compiler/sc7-in.scp | 1218 --- sourcepawn/compiler/sc7.cpp | 653 -- sourcepawn/compiler/sci18n.cpp | 429 - sourcepawn/compiler/sclinux.h | 48 - sourcepawn/compiler/sclist.cpp | 539 -- sourcepawn/compiler/scmemfil.cpp | 165 - sourcepawn/compiler/scstate.cpp | 375 - sourcepawn/compiler/sctracker.cpp | 614 -- sourcepawn/compiler/sctracker.h | 189 - sourcepawn/compiler/scvars.cpp | 120 - sourcepawn/compiler/smx-builder.cpp | 111 - sourcepawn/compiler/smx-builder.h | 217 - sourcepawn/compiler/sp_symhash.cpp | 129 - sourcepawn/compiler/sp_symhash.h | 18 - sourcepawn/compiler/string-pool.h | 146 - .../fail-mix-methodmap-and-class-1.sp | 11 - .../fail-mix-methodmap-and-class-1.txt | 1 - .../fail-mix-methodmap-and-class-2.sp | 11 - .../fail-mix-methodmap-and-class-2.txt | 1 - .../tests/disabled/fail-none-to-obj.sp | 13 - .../tests/disabled/fail-none-to-obj.txt | 1 - .../tests/disabled/fail-obj-to-any.sp | 14 - .../tests/disabled/fail-obj-to-any.txt | 1 - .../tests/disabled/fail-obj-to-multitag.sp | 14 - .../tests/disabled/fail-obj-to-multitag.txt | 1 - .../tests/disabled/fail-obj-to-none.sp | 14 - .../tests/disabled/fail-obj-to-none.txt | 1 - .../tests/disabled/fail-obj-to-varargs.sp | 14 - .../tests/disabled/fail-obj-to-varargs.txt | 1 - .../disabled/fail-object-keyword-as-name.sp | 5 - .../disabled/fail-object-keyword-as-name.txt | 1 - .../tests/disabled/fail-relabel-int-to-obj.sp | 14 - .../disabled/fail-relabel-int-to-obj.txt | 1 - .../tests/disabled/fail-relabel-obj-to-int.sp | 14 - .../disabled/fail-relabel-obj-to-int.txt | 1 - .../tests/fail-array-on-implicit-this.sp | 9 - .../tests/fail-array-on-implicit-this.txt | 1 - .../compiler/tests/fail-assign-null-to-any.sp | 4 - .../tests/fail-assign-null-to-any.txt | 1 - .../tests/fail-assign-string-and-nonstring.sp | 7 - .../fail-assign-string-and-nonstring.txt | 2 - .../compiler/tests/fail-assign-to-this.sp | 12 - .../compiler/tests/fail-assign-to-this.txt | 1 - .../compiler/tests/fail-bad-arg-decls.sp | 15 - .../compiler/tests/fail-bad-arg-decls.txt | 3 - .../compiler/tests/fail-bad-array-decls.sp | 17 - .../compiler/tests/fail-bad-array-decls.txt | 7 - sourcepawn/compiler/tests/fail-bad-void.sp | 13 - sourcepawn/compiler/tests/fail-bad-void.txt | 3 - .../tests/fail-call-non-static-on-type.sp | 12 - .../tests/fail-call-non-static-on-type.txt | 1 - .../tests/fail-call-static-via-instance.sp | 13 - .../tests/fail-call-static-via-instance.txt | 1 - .../tests/fail-callback-returns-array.sp | 16 - .../tests/fail-callback-returns-array.txt | 1 - .../tests/fail-cannot-view-as-void.sp | 3 - .../tests/fail-cannot-view-as-void.txt | 1 - .../tests/fail-coerce-ref-string-to-any.sp | 9 - .../tests/fail-coerce-ref-string-to-any.txt | 1 - .../tests/fail-coerce-string-to-any.sp | 9 - .../tests/fail-coerce-string-to-any.txt | 1 - .../tests/fail-ctor-bad-return-type.sp | 13 - .../tests/fail-ctor-bad-return-type.txt | 1 - .../tests/fail-default-args-in-public.sp | 1 - .../tests/fail-default-args-in-public.txt | 1 - .../compiler/tests/fail-delete-no-dtor.sp | 10 - .../compiler/tests/fail-delete-no-dtor.txt | 1 - .../compiler/tests/fail-dtor-extra-args.sp | 8 - .../compiler/tests/fail-dtor-extra-args.txt | 1 - .../compiler/tests/fail-dtor-non-native.sp | 10 - .../compiler/tests/fail-dtor-non-native.txt | 1 - .../compiler/tests/fail-dtor-returns-value.sp | 8 - .../tests/fail-dtor-returns-value.txt | 1 - .../compiler/tests/fail-duplicate-getter.sp | 9 - .../compiler/tests/fail-duplicate-getter.txt | 1 - .../compiler/tests/fail-duplicate-methods.sp | 8 - .../compiler/tests/fail-duplicate-methods.txt | 1 - .../compiler/tests/fail-duplicate-property.sp | 7 - .../tests/fail-duplicate-property.txt | 1 - .../tests/fail-dynamic-array-bad-type.sp | 4 - .../tests/fail-dynamic-array-bad-type.txt | 1 - .../fail-indeterminate-string-literal.sp | 8 - .../fail-indeterminate-string-literal.txt | 1 - .../tests/fail-method-name-too-long.sp | 7 - .../tests/fail-method-name-too-long.txt | 1 - .../compiler/tests/fail-method-on-array.sp | 12 - .../compiler/tests/fail-method-on-array.txt | 1 - .../compiler/tests/fail-method-on-function.sp | 10 - .../tests/fail-method-on-function.txt | 1 - .../tests/fail-method-requires-brace.sp | 8 - .../tests/fail-method-requires-brace.txt | 1 - .../tests/fail-methodmap-as-rvalue.sp | 17 - .../tests/fail-methodmap-as-rvalue.txt | 1 - .../tests/fail-methodmap-missing-method.sp | 13 - .../tests/fail-methodmap-missing-method.txt | 1 - .../tests/fail-mismatch-on-implicit-this.sp | 9 - .../tests/fail-mismatch-on-implicit-this.txt | 1 - .../compiler/tests/fail-missing-arg-comma.sp | 4 - .../compiler/tests/fail-missing-arg-comma.txt | 1 - .../tests/fail-multi-tag-on-implicit-this.sp | 9 - .../tests/fail-multi-tag-on-implicit-this.txt | 1 - .../tests/fail-new-with-no-constructor.sp | 10 - .../tests/fail-new-with-no-constructor.txt | 1 - .../tests/fail-new-with-no-methodmap.sp | 13 - .../tests/fail-new-with-no-methodmap.txt | 1 - .../tests/fail-new-with-non-nullable.sp | 11 - .../tests/fail-new-with-non-nullable.txt | 1 - sourcepawn/compiler/tests/fail-newdecls.sp | 15 - sourcepawn/compiler/tests/fail-newdecls.txt | 5 - .../tests/fail-no-tag-on-implicit-this.sp | 9 - .../tests/fail-no-tag-on-implicit-this.txt | 1 - .../compiler/tests/fail-nullable-needs-new.sp | 11 - .../tests/fail-nullable-needs-new.txt | 1 - .../compiler/tests/fail-old-decl-new-types.sp | 8 - .../tests/fail-old-decl-new-types.txt | 3 - .../tests/fail-property-bad-return-type.sp | 12 - .../tests/fail-property-bad-return-type.txt | 1 - .../tests/fail-property-bad-return-value.txt | 1 - .../tests/fail-property-bad-this-type.sp | 12 - .../tests/fail-property-bad-this-type.txt | 1 - .../tests/fail-ref-on-implicit-this.sp | 9 - .../tests/fail-ref-on-implicit-this.txt | 1 - .../compiler/tests/fail-sizeof-default-arg.sp | 9 - .../tests/fail-sizeof-default-arg.txt | 1 - .../tests/fail-tag-enum-as-implicit-int.sp | 23 - .../tests/fail-tag-enum-as-implicit-int.txt | 1 - .../tests/fail-this-outside-method.sp | 3 - .../tests/fail-this-outside-method.txt | 1 - .../compiler/tests/ok-any-in-newdecl.sp | 3 - sourcepawn/compiler/tests/ok-bad-int-cast.sp | 4 - sourcepawn/compiler/tests/ok-base-dtor.sp | 15 - .../compiler/tests/ok-base-type-as-thistag.sp | 14 - .../compiler/tests/ok-call-static-method.sp | 12 - sourcepawn/compiler/tests/ok-chaining.sp | 38 - sourcepawn/compiler/tests/ok-class-arg.sp | 7 - .../compiler/tests/ok-coerce-on-operators.sp | 18 - sourcepawn/compiler/tests/ok-ctor-dtor.sp | 12 - sourcepawn/compiler/tests/ok-dynamic-char.sp | 5 - sourcepawn/compiler/tests/ok-for-newdecl.sp | 5 - sourcepawn/compiler/tests/ok-inheritance.sp | 14 - .../compiler/tests/ok-inline-methods.sp | 13 - .../compiler/tests/ok-inline-natives.sp | 17 - .../compiler/tests/ok-local-dynamic-bool.sp | 5 - .../compiler/tests/ok-method-on-const.sp | 14 - .../compiler/tests/ok-method-on-constref.sp | 16 - .../compiler/tests/ok-method-on-element.sp | 11 - sourcepawn/compiler/tests/ok-method-on-ref.sp | 16 - .../compiler/tests/ok-method-on-scalar.sp | 13 - .../compiler/tests/ok-methodmap-semis.sp | 20 - sourcepawn/compiler/tests/ok-new-decl-args.sp | 44 - .../tests/ok-new-dynamic-array-syntax.sp | 10 - .../tests/ok-new-with-nullable-methodmap.sp | 15 - sourcepawn/compiler/tests/ok-newdecl-const.sp | 12 - sourcepawn/compiler/tests/ok-newdecls.sp | 50 - sourcepawn/compiler/tests/ok-null-compare.sp | 19 - sourcepawn/compiler/tests/ok-properties.sp | 29 - .../compiler/tests/ok-reparse-delete.sp | 12 - .../compiler/tests/ok-setter-no-getter.sp | 12 - sourcepawn/compiler/tests/ok-static-stock.sp | 13 - .../compiler/tests/ok-static-stocks-1.sp | 5 - .../compiler/tests/ok-static-stocks-2.sp | 7 - .../tests/ok-trailing-comma-in-literal.sp | 20 - .../tests/ok-typed-vararg-in-new-function.sp | 7 - .../compiler/tests/ok-typedef-func-chars.sp | 26 - .../tests/ok-use-aliased-constructor.sp | 12 - sourcepawn/compiler/tests/ok-varargs.sp | 7 - .../compiler/tests/ok-view-int-as-float.sp | 3 - sourcepawn/compiler/tests/runtests.py | 83 - sourcepawn/compiler/tests/warn-bad-upcast.sp | 15 - sourcepawn/compiler/tests/warn-bad-upcast.txt | 1 - .../compiler/tests/warn-oldstyle-cast.sp | 18 - .../compiler/tests/warn-oldstyle-cast.txt | 2 - sourcepawn/compiler/tokenbuffer.h | 35 - sourcepawn/compiler/version.rc | 52 - sourcepawn/include/smx/smx-headers.h | 177 - sourcepawn/include/smx/smx-rtti.h | 218 - sourcepawn/include/smx/smx-v1-opcodes.h | 269 - sourcepawn/include/smx/smx-v1.h | 209 - sourcepawn/include/sp_typeutil.h | 65 - sourcepawn/include/sp_vm_api.h | 1618 ---- sourcepawn/include/sp_vm_base.h | 51 - sourcepawn/include/sp_vm_types.h | 228 - sourcepawn/third_party/zlib/adler32.c | 149 - sourcepawn/third_party/zlib/compress.c | 79 - sourcepawn/third_party/zlib/crc32.c | 424 - sourcepawn/third_party/zlib/crc32.h | 441 - sourcepawn/third_party/zlib/deflate.c | 1737 ---- sourcepawn/third_party/zlib/deflate.h | 331 - sourcepawn/third_party/zlib/gzio.c | 1026 --- sourcepawn/third_party/zlib/infback.c | 624 -- sourcepawn/third_party/zlib/inffast.c | 319 - sourcepawn/third_party/zlib/inffast.h | 11 - sourcepawn/third_party/zlib/inffixed.h | 94 - sourcepawn/third_party/zlib/inflate.c | 1369 --- sourcepawn/third_party/zlib/inflate.h | 115 - sourcepawn/third_party/zlib/inftrees.c | 330 - sourcepawn/third_party/zlib/inftrees.h | 55 - sourcepawn/third_party/zlib/trees.c | 1220 --- sourcepawn/third_party/zlib/trees.h | 128 - sourcepawn/third_party/zlib/uncompr.c | 61 - sourcepawn/third_party/zlib/zconf.h | 281 - sourcepawn/third_party/zlib/zlib.h | 1357 --- sourcepawn/third_party/zlib/zutil.c | 319 - sourcepawn/third_party/zlib/zutil.h | 269 - sourcepawn/vm/AMBuilder | 94 - sourcepawn/vm/Makefile | 119 - sourcepawn/vm/Makefile.shell | 120 - sourcepawn/vm/api.cpp | 405 - sourcepawn/vm/api.h | 79 - sourcepawn/vm/assembler.h | 305 - sourcepawn/vm/code-allocator.cpp | 419 - sourcepawn/vm/code-allocator.h | 47 - sourcepawn/vm/code-stubs.cpp | 40 - sourcepawn/vm/code-stubs.h | 56 - sourcepawn/vm/compiled-function.cpp | 71 - sourcepawn/vm/compiled-function.h | 79 - sourcepawn/vm/dll_exports.cpp | 282 - sourcepawn/vm/dll_exports.h | 47 - sourcepawn/vm/environment.cpp | 402 - sourcepawn/vm/environment.h | 200 - sourcepawn/vm/file-utils.cpp | 52 - sourcepawn/vm/file-utils.h | 47 - sourcepawn/vm/legacy-image.h | 138 - sourcepawn/vm/md5/md5.cpp | 475 - sourcepawn/vm/md5/md5.h | 106 - sourcepawn/vm/opcodes.cpp | 141 - sourcepawn/vm/opcodes.h | 40 - sourcepawn/vm/plugin-context.cpp | 953 -- sourcepawn/vm/plugin-context.h | 193 - sourcepawn/vm/plugin-runtime.cpp | 494 - sourcepawn/vm/plugin-runtime.h | 156 - sourcepawn/vm/scripted-invoker.cpp | 354 - sourcepawn/vm/scripted-invoker.h | 104 - sourcepawn/vm/smx-v1-image.cpp | 617 -- sourcepawn/vm/smx-v1-image.h | 204 - sourcepawn/vm/stack-frames.cpp | 227 - sourcepawn/vm/stack-frames.h | 135 - sourcepawn/vm/version.rc | 103 - sourcepawn/vm/watchdog_timer.cpp | 165 - sourcepawn/vm/watchdog_timer.h | 67 - sourcepawn/vm/x86/assembler-x86.cpp | 33 - sourcepawn/vm/x86/assembler-x86.h | 977 -- sourcepawn/vm/x86/code-stubs-x86.cpp | 141 - sourcepawn/vm/x86/frames-x86.h | 83 - sourcepawn/vm/x86/jit_x86.cpp | 1833 ---- sourcepawn/vm/x86/jit_x86.h | 170 - sourcepawn/vm/x86/macro-assembler-x86.h | 104 - sourcepawn/vm/x86/x86-utils.cpp | 30 - sourcepawn/vm/x86/x86-utils.h | 27 - 276 files changed, 29 insertions(+), 52221 deletions(-) create mode 160000 sourcepawn delete mode 100644 sourcepawn/compiler/AMBuilder delete mode 100644 sourcepawn/compiler/Makefile delete mode 100644 sourcepawn/compiler/amx.h delete mode 100644 sourcepawn/compiler/amxdbg.h delete mode 100644 sourcepawn/compiler/binreloc.c delete mode 100644 sourcepawn/compiler/binreloc.h delete mode 100644 sourcepawn/compiler/getch.h delete mode 100644 sourcepawn/compiler/libpawnc.cpp delete mode 100644 sourcepawn/compiler/lstring.cpp delete mode 100644 sourcepawn/compiler/lstring.h delete mode 100644 sourcepawn/compiler/memfile.cpp delete mode 100644 sourcepawn/compiler/memfile.h delete mode 100644 sourcepawn/compiler/memory-buffer.h delete mode 100644 sourcepawn/compiler/osdefs.h delete mode 100644 sourcepawn/compiler/pawn.ico delete mode 100644 sourcepawn/compiler/pawncc.cpp delete mode 100644 sourcepawn/compiler/sc.h delete mode 100644 sourcepawn/compiler/sc1.cpp delete mode 100644 sourcepawn/compiler/sc2.cpp delete mode 100644 sourcepawn/compiler/sc3.cpp delete mode 100644 sourcepawn/compiler/sc4.cpp delete mode 100644 sourcepawn/compiler/sc5-in.scp delete mode 100644 sourcepawn/compiler/sc5.cpp delete mode 100644 sourcepawn/compiler/sc6.cpp delete mode 100644 sourcepawn/compiler/sc7-in.scp delete mode 100644 sourcepawn/compiler/sc7.cpp delete mode 100644 sourcepawn/compiler/sci18n.cpp delete mode 100644 sourcepawn/compiler/sclinux.h delete mode 100644 sourcepawn/compiler/sclist.cpp delete mode 100644 sourcepawn/compiler/scmemfil.cpp delete mode 100644 sourcepawn/compiler/scstate.cpp delete mode 100644 sourcepawn/compiler/sctracker.cpp delete mode 100644 sourcepawn/compiler/sctracker.h delete mode 100644 sourcepawn/compiler/scvars.cpp delete mode 100644 sourcepawn/compiler/smx-builder.cpp delete mode 100644 sourcepawn/compiler/smx-builder.h delete mode 100644 sourcepawn/compiler/sp_symhash.cpp delete mode 100644 sourcepawn/compiler/sp_symhash.h delete mode 100644 sourcepawn/compiler/string-pool.h delete mode 100644 sourcepawn/compiler/tests/disabled/fail-mix-methodmap-and-class-1.sp delete mode 100644 sourcepawn/compiler/tests/disabled/fail-mix-methodmap-and-class-1.txt delete mode 100644 sourcepawn/compiler/tests/disabled/fail-mix-methodmap-and-class-2.sp delete mode 100644 sourcepawn/compiler/tests/disabled/fail-mix-methodmap-and-class-2.txt delete mode 100644 sourcepawn/compiler/tests/disabled/fail-none-to-obj.sp delete mode 100644 sourcepawn/compiler/tests/disabled/fail-none-to-obj.txt delete mode 100644 sourcepawn/compiler/tests/disabled/fail-obj-to-any.sp delete mode 100644 sourcepawn/compiler/tests/disabled/fail-obj-to-any.txt delete mode 100644 sourcepawn/compiler/tests/disabled/fail-obj-to-multitag.sp delete mode 100644 sourcepawn/compiler/tests/disabled/fail-obj-to-multitag.txt delete mode 100644 sourcepawn/compiler/tests/disabled/fail-obj-to-none.sp delete mode 100644 sourcepawn/compiler/tests/disabled/fail-obj-to-none.txt delete mode 100644 sourcepawn/compiler/tests/disabled/fail-obj-to-varargs.sp delete mode 100644 sourcepawn/compiler/tests/disabled/fail-obj-to-varargs.txt delete mode 100644 sourcepawn/compiler/tests/disabled/fail-object-keyword-as-name.sp delete mode 100644 sourcepawn/compiler/tests/disabled/fail-object-keyword-as-name.txt delete mode 100644 sourcepawn/compiler/tests/disabled/fail-relabel-int-to-obj.sp delete mode 100644 sourcepawn/compiler/tests/disabled/fail-relabel-int-to-obj.txt delete mode 100644 sourcepawn/compiler/tests/disabled/fail-relabel-obj-to-int.sp delete mode 100644 sourcepawn/compiler/tests/disabled/fail-relabel-obj-to-int.txt delete mode 100644 sourcepawn/compiler/tests/fail-array-on-implicit-this.sp delete mode 100644 sourcepawn/compiler/tests/fail-array-on-implicit-this.txt delete mode 100644 sourcepawn/compiler/tests/fail-assign-null-to-any.sp delete mode 100644 sourcepawn/compiler/tests/fail-assign-null-to-any.txt delete mode 100644 sourcepawn/compiler/tests/fail-assign-string-and-nonstring.sp delete mode 100644 sourcepawn/compiler/tests/fail-assign-string-and-nonstring.txt delete mode 100644 sourcepawn/compiler/tests/fail-assign-to-this.sp delete mode 100644 sourcepawn/compiler/tests/fail-assign-to-this.txt delete mode 100644 sourcepawn/compiler/tests/fail-bad-arg-decls.sp delete mode 100644 sourcepawn/compiler/tests/fail-bad-arg-decls.txt delete mode 100644 sourcepawn/compiler/tests/fail-bad-array-decls.sp delete mode 100644 sourcepawn/compiler/tests/fail-bad-array-decls.txt delete mode 100644 sourcepawn/compiler/tests/fail-bad-void.sp delete mode 100644 sourcepawn/compiler/tests/fail-bad-void.txt delete mode 100644 sourcepawn/compiler/tests/fail-call-non-static-on-type.sp delete mode 100644 sourcepawn/compiler/tests/fail-call-non-static-on-type.txt delete mode 100644 sourcepawn/compiler/tests/fail-call-static-via-instance.sp delete mode 100644 sourcepawn/compiler/tests/fail-call-static-via-instance.txt delete mode 100644 sourcepawn/compiler/tests/fail-callback-returns-array.sp delete mode 100644 sourcepawn/compiler/tests/fail-callback-returns-array.txt delete mode 100644 sourcepawn/compiler/tests/fail-cannot-view-as-void.sp delete mode 100644 sourcepawn/compiler/tests/fail-cannot-view-as-void.txt delete mode 100644 sourcepawn/compiler/tests/fail-coerce-ref-string-to-any.sp delete mode 100644 sourcepawn/compiler/tests/fail-coerce-ref-string-to-any.txt delete mode 100644 sourcepawn/compiler/tests/fail-coerce-string-to-any.sp delete mode 100644 sourcepawn/compiler/tests/fail-coerce-string-to-any.txt delete mode 100644 sourcepawn/compiler/tests/fail-ctor-bad-return-type.sp delete mode 100644 sourcepawn/compiler/tests/fail-ctor-bad-return-type.txt delete mode 100644 sourcepawn/compiler/tests/fail-default-args-in-public.sp delete mode 100644 sourcepawn/compiler/tests/fail-default-args-in-public.txt delete mode 100644 sourcepawn/compiler/tests/fail-delete-no-dtor.sp delete mode 100644 sourcepawn/compiler/tests/fail-delete-no-dtor.txt delete mode 100644 sourcepawn/compiler/tests/fail-dtor-extra-args.sp delete mode 100644 sourcepawn/compiler/tests/fail-dtor-extra-args.txt delete mode 100644 sourcepawn/compiler/tests/fail-dtor-non-native.sp delete mode 100644 sourcepawn/compiler/tests/fail-dtor-non-native.txt delete mode 100644 sourcepawn/compiler/tests/fail-dtor-returns-value.sp delete mode 100644 sourcepawn/compiler/tests/fail-dtor-returns-value.txt delete mode 100644 sourcepawn/compiler/tests/fail-duplicate-getter.sp delete mode 100644 sourcepawn/compiler/tests/fail-duplicate-getter.txt delete mode 100644 sourcepawn/compiler/tests/fail-duplicate-methods.sp delete mode 100644 sourcepawn/compiler/tests/fail-duplicate-methods.txt delete mode 100644 sourcepawn/compiler/tests/fail-duplicate-property.sp delete mode 100644 sourcepawn/compiler/tests/fail-duplicate-property.txt delete mode 100644 sourcepawn/compiler/tests/fail-dynamic-array-bad-type.sp delete mode 100644 sourcepawn/compiler/tests/fail-dynamic-array-bad-type.txt delete mode 100644 sourcepawn/compiler/tests/fail-indeterminate-string-literal.sp delete mode 100644 sourcepawn/compiler/tests/fail-indeterminate-string-literal.txt delete mode 100644 sourcepawn/compiler/tests/fail-method-name-too-long.sp delete mode 100644 sourcepawn/compiler/tests/fail-method-name-too-long.txt delete mode 100644 sourcepawn/compiler/tests/fail-method-on-array.sp delete mode 100644 sourcepawn/compiler/tests/fail-method-on-array.txt delete mode 100644 sourcepawn/compiler/tests/fail-method-on-function.sp delete mode 100644 sourcepawn/compiler/tests/fail-method-on-function.txt delete mode 100644 sourcepawn/compiler/tests/fail-method-requires-brace.sp delete mode 100644 sourcepawn/compiler/tests/fail-method-requires-brace.txt delete mode 100644 sourcepawn/compiler/tests/fail-methodmap-as-rvalue.sp delete mode 100644 sourcepawn/compiler/tests/fail-methodmap-as-rvalue.txt delete mode 100644 sourcepawn/compiler/tests/fail-methodmap-missing-method.sp delete mode 100644 sourcepawn/compiler/tests/fail-methodmap-missing-method.txt delete mode 100644 sourcepawn/compiler/tests/fail-mismatch-on-implicit-this.sp delete mode 100644 sourcepawn/compiler/tests/fail-mismatch-on-implicit-this.txt delete mode 100644 sourcepawn/compiler/tests/fail-missing-arg-comma.sp delete mode 100644 sourcepawn/compiler/tests/fail-missing-arg-comma.txt delete mode 100644 sourcepawn/compiler/tests/fail-multi-tag-on-implicit-this.sp delete mode 100644 sourcepawn/compiler/tests/fail-multi-tag-on-implicit-this.txt delete mode 100644 sourcepawn/compiler/tests/fail-new-with-no-constructor.sp delete mode 100644 sourcepawn/compiler/tests/fail-new-with-no-constructor.txt delete mode 100644 sourcepawn/compiler/tests/fail-new-with-no-methodmap.sp delete mode 100644 sourcepawn/compiler/tests/fail-new-with-no-methodmap.txt delete mode 100644 sourcepawn/compiler/tests/fail-new-with-non-nullable.sp delete mode 100644 sourcepawn/compiler/tests/fail-new-with-non-nullable.txt delete mode 100644 sourcepawn/compiler/tests/fail-newdecls.sp delete mode 100644 sourcepawn/compiler/tests/fail-newdecls.txt delete mode 100644 sourcepawn/compiler/tests/fail-no-tag-on-implicit-this.sp delete mode 100644 sourcepawn/compiler/tests/fail-no-tag-on-implicit-this.txt delete mode 100644 sourcepawn/compiler/tests/fail-nullable-needs-new.sp delete mode 100644 sourcepawn/compiler/tests/fail-nullable-needs-new.txt delete mode 100644 sourcepawn/compiler/tests/fail-old-decl-new-types.sp delete mode 100644 sourcepawn/compiler/tests/fail-old-decl-new-types.txt delete mode 100644 sourcepawn/compiler/tests/fail-property-bad-return-type.sp delete mode 100644 sourcepawn/compiler/tests/fail-property-bad-return-type.txt delete mode 100644 sourcepawn/compiler/tests/fail-property-bad-return-value.txt delete mode 100644 sourcepawn/compiler/tests/fail-property-bad-this-type.sp delete mode 100644 sourcepawn/compiler/tests/fail-property-bad-this-type.txt delete mode 100644 sourcepawn/compiler/tests/fail-ref-on-implicit-this.sp delete mode 100644 sourcepawn/compiler/tests/fail-ref-on-implicit-this.txt delete mode 100644 sourcepawn/compiler/tests/fail-sizeof-default-arg.sp delete mode 100644 sourcepawn/compiler/tests/fail-sizeof-default-arg.txt delete mode 100644 sourcepawn/compiler/tests/fail-tag-enum-as-implicit-int.sp delete mode 100644 sourcepawn/compiler/tests/fail-tag-enum-as-implicit-int.txt delete mode 100644 sourcepawn/compiler/tests/fail-this-outside-method.sp delete mode 100644 sourcepawn/compiler/tests/fail-this-outside-method.txt delete mode 100644 sourcepawn/compiler/tests/ok-any-in-newdecl.sp delete mode 100644 sourcepawn/compiler/tests/ok-bad-int-cast.sp delete mode 100644 sourcepawn/compiler/tests/ok-base-dtor.sp delete mode 100644 sourcepawn/compiler/tests/ok-base-type-as-thistag.sp delete mode 100644 sourcepawn/compiler/tests/ok-call-static-method.sp delete mode 100644 sourcepawn/compiler/tests/ok-chaining.sp delete mode 100644 sourcepawn/compiler/tests/ok-class-arg.sp delete mode 100644 sourcepawn/compiler/tests/ok-coerce-on-operators.sp delete mode 100644 sourcepawn/compiler/tests/ok-ctor-dtor.sp delete mode 100644 sourcepawn/compiler/tests/ok-dynamic-char.sp delete mode 100644 sourcepawn/compiler/tests/ok-for-newdecl.sp delete mode 100644 sourcepawn/compiler/tests/ok-inheritance.sp delete mode 100644 sourcepawn/compiler/tests/ok-inline-methods.sp delete mode 100644 sourcepawn/compiler/tests/ok-inline-natives.sp delete mode 100644 sourcepawn/compiler/tests/ok-local-dynamic-bool.sp delete mode 100644 sourcepawn/compiler/tests/ok-method-on-const.sp delete mode 100644 sourcepawn/compiler/tests/ok-method-on-constref.sp delete mode 100644 sourcepawn/compiler/tests/ok-method-on-element.sp delete mode 100644 sourcepawn/compiler/tests/ok-method-on-ref.sp delete mode 100644 sourcepawn/compiler/tests/ok-method-on-scalar.sp delete mode 100644 sourcepawn/compiler/tests/ok-methodmap-semis.sp delete mode 100644 sourcepawn/compiler/tests/ok-new-decl-args.sp delete mode 100644 sourcepawn/compiler/tests/ok-new-dynamic-array-syntax.sp delete mode 100644 sourcepawn/compiler/tests/ok-new-with-nullable-methodmap.sp delete mode 100644 sourcepawn/compiler/tests/ok-newdecl-const.sp delete mode 100644 sourcepawn/compiler/tests/ok-newdecls.sp delete mode 100644 sourcepawn/compiler/tests/ok-null-compare.sp delete mode 100644 sourcepawn/compiler/tests/ok-properties.sp delete mode 100644 sourcepawn/compiler/tests/ok-reparse-delete.sp delete mode 100644 sourcepawn/compiler/tests/ok-setter-no-getter.sp delete mode 100644 sourcepawn/compiler/tests/ok-static-stock.sp delete mode 100644 sourcepawn/compiler/tests/ok-static-stocks-1.sp delete mode 100644 sourcepawn/compiler/tests/ok-static-stocks-2.sp delete mode 100644 sourcepawn/compiler/tests/ok-trailing-comma-in-literal.sp delete mode 100644 sourcepawn/compiler/tests/ok-typed-vararg-in-new-function.sp delete mode 100644 sourcepawn/compiler/tests/ok-typedef-func-chars.sp delete mode 100644 sourcepawn/compiler/tests/ok-use-aliased-constructor.sp delete mode 100644 sourcepawn/compiler/tests/ok-varargs.sp delete mode 100644 sourcepawn/compiler/tests/ok-view-int-as-float.sp delete mode 100644 sourcepawn/compiler/tests/runtests.py delete mode 100644 sourcepawn/compiler/tests/warn-bad-upcast.sp delete mode 100644 sourcepawn/compiler/tests/warn-bad-upcast.txt delete mode 100644 sourcepawn/compiler/tests/warn-oldstyle-cast.sp delete mode 100644 sourcepawn/compiler/tests/warn-oldstyle-cast.txt delete mode 100644 sourcepawn/compiler/tokenbuffer.h delete mode 100644 sourcepawn/compiler/version.rc delete mode 100644 sourcepawn/include/smx/smx-headers.h delete mode 100644 sourcepawn/include/smx/smx-rtti.h delete mode 100644 sourcepawn/include/smx/smx-v1-opcodes.h delete mode 100644 sourcepawn/include/smx/smx-v1.h delete mode 100644 sourcepawn/include/sp_typeutil.h delete mode 100644 sourcepawn/include/sp_vm_api.h delete mode 100644 sourcepawn/include/sp_vm_base.h delete mode 100644 sourcepawn/include/sp_vm_types.h delete mode 100644 sourcepawn/third_party/zlib/adler32.c delete mode 100644 sourcepawn/third_party/zlib/compress.c delete mode 100644 sourcepawn/third_party/zlib/crc32.c delete mode 100644 sourcepawn/third_party/zlib/crc32.h delete mode 100644 sourcepawn/third_party/zlib/deflate.c delete mode 100644 sourcepawn/third_party/zlib/deflate.h delete mode 100644 sourcepawn/third_party/zlib/gzio.c delete mode 100644 sourcepawn/third_party/zlib/infback.c delete mode 100644 sourcepawn/third_party/zlib/inffast.c delete mode 100644 sourcepawn/third_party/zlib/inffast.h delete mode 100644 sourcepawn/third_party/zlib/inffixed.h delete mode 100644 sourcepawn/third_party/zlib/inflate.c delete mode 100644 sourcepawn/third_party/zlib/inflate.h delete mode 100644 sourcepawn/third_party/zlib/inftrees.c delete mode 100644 sourcepawn/third_party/zlib/inftrees.h delete mode 100644 sourcepawn/third_party/zlib/trees.c delete mode 100644 sourcepawn/third_party/zlib/trees.h delete mode 100644 sourcepawn/third_party/zlib/uncompr.c delete mode 100644 sourcepawn/third_party/zlib/zconf.h delete mode 100644 sourcepawn/third_party/zlib/zlib.h delete mode 100644 sourcepawn/third_party/zlib/zutil.c delete mode 100644 sourcepawn/third_party/zlib/zutil.h delete mode 100644 sourcepawn/vm/AMBuilder delete mode 100644 sourcepawn/vm/Makefile delete mode 100644 sourcepawn/vm/Makefile.shell delete mode 100644 sourcepawn/vm/api.cpp delete mode 100644 sourcepawn/vm/api.h delete mode 100644 sourcepawn/vm/assembler.h delete mode 100644 sourcepawn/vm/code-allocator.cpp delete mode 100644 sourcepawn/vm/code-allocator.h delete mode 100644 sourcepawn/vm/code-stubs.cpp delete mode 100644 sourcepawn/vm/code-stubs.h delete mode 100644 sourcepawn/vm/compiled-function.cpp delete mode 100644 sourcepawn/vm/compiled-function.h delete mode 100644 sourcepawn/vm/dll_exports.cpp delete mode 100644 sourcepawn/vm/dll_exports.h delete mode 100644 sourcepawn/vm/environment.cpp delete mode 100644 sourcepawn/vm/environment.h delete mode 100644 sourcepawn/vm/file-utils.cpp delete mode 100644 sourcepawn/vm/file-utils.h delete mode 100644 sourcepawn/vm/legacy-image.h delete mode 100644 sourcepawn/vm/md5/md5.cpp delete mode 100644 sourcepawn/vm/md5/md5.h delete mode 100644 sourcepawn/vm/opcodes.cpp delete mode 100644 sourcepawn/vm/opcodes.h delete mode 100644 sourcepawn/vm/plugin-context.cpp delete mode 100644 sourcepawn/vm/plugin-context.h delete mode 100644 sourcepawn/vm/plugin-runtime.cpp delete mode 100644 sourcepawn/vm/plugin-runtime.h delete mode 100644 sourcepawn/vm/scripted-invoker.cpp delete mode 100644 sourcepawn/vm/scripted-invoker.h delete mode 100644 sourcepawn/vm/smx-v1-image.cpp delete mode 100644 sourcepawn/vm/smx-v1-image.h delete mode 100644 sourcepawn/vm/stack-frames.cpp delete mode 100644 sourcepawn/vm/stack-frames.h delete mode 100644 sourcepawn/vm/version.rc delete mode 100644 sourcepawn/vm/watchdog_timer.cpp delete mode 100644 sourcepawn/vm/watchdog_timer.h delete mode 100644 sourcepawn/vm/x86/assembler-x86.cpp delete mode 100644 sourcepawn/vm/x86/assembler-x86.h delete mode 100644 sourcepawn/vm/x86/code-stubs-x86.cpp delete mode 100644 sourcepawn/vm/x86/frames-x86.h delete mode 100644 sourcepawn/vm/x86/jit_x86.cpp delete mode 100644 sourcepawn/vm/x86/jit_x86.h delete mode 100644 sourcepawn/vm/x86/macro-assembler-x86.h delete mode 100644 sourcepawn/vm/x86/x86-utils.cpp delete mode 100644 sourcepawn/vm/x86/x86-utils.h diff --git a/.gitmodules b/.gitmodules index 40c909fb..fde0c20f 100644 --- a/.gitmodules +++ b/.gitmodules @@ -1,3 +1,6 @@ [submodule "public/amtl"] path = public/amtl url = https://github.com/alliedmodders/amtl +[submodule "sourcepawn"] + path = sourcepawn + url = https://github.com/alliedmodders/sourcepawn diff --git a/AMBuildScript b/AMBuildScript index 65305bdf..c843b033 100644 --- a/AMBuildScript +++ b/AMBuildScript @@ -172,7 +172,7 @@ class SMConfig(object): '-m32', ] cxx.cxxflags += [ - '-std=c++11', + '-std=c++11', ] have_gcc = cxx.vendor == 'gcc' @@ -226,7 +226,6 @@ class SMConfig(object): ] cxx.linkflags += [ '/MACHINE:X86', - '/SUBSYSTEM:WINDOWS', 'kernel32.lib', 'user32.lib', 'gdi32.lib', @@ -286,10 +285,15 @@ class SMConfig(object): 'SOURCEMOD_BUILD', 'SM_USE_VERSIONLIB', ] + cxx.includes += [ + os.path.join(builder.sourcePath, 'public'), + ] if self.use_auto_versioning(): cxx.defines += ['SM_GENERATED_BUILD'] - cxx.includes += [os.path.join(builder.buildPath, 'includes')] - cxx.includes += [os.path.join(builder.sourcePath, 'versionlib')] + cxx.includes += [ + os.path.join(builder.buildPath, 'includes'), + os.path.join(builder.sourcePath, 'versionlib'), + ] def AddVersioning(self, binary): if builder.target_platform == 'windows': @@ -313,17 +317,20 @@ class SMConfig(object): def Library(self, context, name): binary = context.compiler.Library(name) + if binary.compiler.like('msvc'): + binary.compiler.linkflags += ['/SUBSYSTEM:WINDOWS'] return self.AddVersioning(binary) def Program(self, context, name): binary = context.compiler.Program(name) + if binary.compiler.like('msvc'): + binary.compiler.linkflags += ['/SUBSYSTEM:CONSOLE'] return self.AddVersioning(binary) def ConfigureForExtension(self, context, compiler): compiler.cxxincludes += [ os.path.join(context.currentSourcePath), os.path.join(context.currentSourcePath, 'sdk'), - os.path.join(builder.sourcePath, 'public'), os.path.join(builder.sourcePath, 'public', 'extensions'), os.path.join(builder.sourcePath, 'sourcepawn', 'include'), os.path.join(builder.sourcePath, 'public', 'amtl', 'include'), @@ -491,6 +498,19 @@ if SM.use_auto_versioning(): { 'SM': SM } ) +# Build SourcePawn externally. +with builder.Context('sourcepawn') as context: + SourcePawn = builder.RunScript('sourcepawn/AMBuildScript', {}) + SP = SourcePawn( + root = SM, + amtl = os.path.join(builder.sourcePath, 'public', 'amtl'), + ) + SP.BuildCore() + SM.spcomp = SP.spcomp + SM.binaries += [ + SP.libsourcepawn + ] + BuildScripts = [ 'loader/AMBuilder', 'core/AMBuilder', @@ -508,8 +528,6 @@ BuildScripts = [ 'extensions/tf2/AMBuilder', 'extensions/topmenus/AMBuilder', 'extensions/updater/AMBuilder', - 'sourcepawn/compiler/AMBuilder', - 'sourcepawn/vm/AMBuilder', ] if builder.backend == 'amb2': diff --git a/sourcepawn b/sourcepawn new file mode 160000 index 00000000..1b306287 --- /dev/null +++ b/sourcepawn @@ -0,0 +1 @@ +Subproject commit 1b3062875df9121a3fd553673b1a6c6c412d9b08 diff --git a/sourcepawn/compiler/AMBuilder b/sourcepawn/compiler/AMBuilder deleted file mode 100644 index c52dcf47..00000000 --- a/sourcepawn/compiler/AMBuilder +++ /dev/null @@ -1,79 +0,0 @@ -# vim: set sts=2 ts=8 sw=2 tw=99 et ft=python: -import os - -binary = SM.Program(builder, 'spcomp') -compiler = binary.compiler -compiler.includes += [ - os.path.join(builder.sourcePath, 'public'), - os.path.join(builder.sourcePath, 'public', 'amtl', 'include'), - os.path.join(builder.sourcePath, 'public', 'sourcepawn'), - os.path.join(builder.currentSourcePath, '..', 'include'), - os.path.join(builder.currentSourcePath, '..', 'third_party'), - os.path.join(builder.buildPath, 'includes'), - os.path.join(builder.buildPath, builder.buildFolder), -] - -if compiler.cc.behavior == 'gcc': - compiler.cflags += ['-Wno-format'] - compiler.c_only_flags += ['-std=c99'] - if builder.target_platform == 'linux': - compiler.postlink += ['-lm'] - compiler.postlink += ['-lstdc++'] -elif compiler.cc.behavior == 'msvc': - compiler.linkflags.remove('/SUBSYSTEM:WINDOWS') - compiler.linkflags.append('/SUBSYSTEM:CONSOLE') - compiler.cxxflags.remove('/TP') - -compiler.defines += ['HAVE_STDINT_H'] -if builder.target_platform == 'linux': - compiler.defines += [ - 'LINUX', - 'AMX_ANSIONLY', - 'ENABLE_BINRELOC', - '_GNU_SOURCE' - ] -elif builder.target_platform == 'mac': - compiler.defines += [ - 'DARWIN', - 'AMX_ANSIONLY', - 'ENABLE_BINRELOC', - 'HAVE_SAFESTR' - ] - -binary.sources += [ - 'libpawnc.cpp', - 'lstring.cpp', - 'memfile.cpp', - 'pawncc.cpp', - 'sc1.cpp', - 'sc2.cpp', - 'sc3.cpp', - 'sc4.cpp', - 'sc5.cpp', - 'sc6.cpp', - 'sc7.cpp', - 'sci18n.cpp', - 'sclist.cpp', - 'scmemfil.cpp', - 'scstate.cpp', - 'sctracker.cpp', - 'scvars.cpp', - 'smx-builder.cpp', - 'sp_symhash.cpp', - '../third_party/zlib/adler32.c', - '../third_party/zlib/compress.c', - '../third_party/zlib/crc32.c', - '../third_party/zlib/deflate.c', - '../third_party/zlib/gzio.c', - '../third_party/zlib/infback.c', - '../third_party/zlib/inffast.c', - '../third_party/zlib/inflate.c', - '../third_party/zlib/inftrees.c', - '../third_party/zlib/trees.c', - '../third_party/zlib/uncompr.c', - '../third_party/zlib/zutil.c', -] -if builder.target_platform != 'windows': - binary.sources.append('binreloc.c') - -SM.spcomp = builder.Add(binary) diff --git a/sourcepawn/compiler/Makefile b/sourcepawn/compiler/Makefile deleted file mode 100644 index 1d5c4f59..00000000 --- a/sourcepawn/compiler/Makefile +++ /dev/null @@ -1,74 +0,0 @@ -# (C)2004-2008 SourceMod Development Team -# Makefile written by David "BAILOPAN" Anderson - -SMSDK = ../.. - -##################################### -### EDIT BELOW FOR OTHER PROJECTS ### -##################################### - -BINARY = spcomp - -OBJECTS = binreloc.c libpawnc.c lstring.c memfile.c pawncc.c sc1.c sc2.c sc3.c sc4.c \ - sc5.c sc6.c sc7.c scexpand.c sci18n.c sclist.c scmemfil.c scstate.c sctracker.c \ - scvars.c sp_file.c sp_symhash.c -OBJECTS += zlib/adler32.c zlib/compress.c zlib/crc32.c zlib/deflate.c zlib/gzio.c \ - zlib/infback.c zlib/inffast.c zlib/inflate.c zlib/inftrees.c zlib/trees.c \ - zlib/uncompr.c zlib/zutil.c - -############################################## -### CONFIGURE ANY OTHER FLAGS/OPTIONS HERE ### -############################################## - -C_OPT_FLAGS = -DNDEBUG -O3 -funroll-loops -pipe -fno-strict-aliasing -fomit-frame-pointer -C_DEBUG_FLAGS = -D_DEBUG -DDEBUG -g -ggdb3 -C_GCC4_FLAGS = -fvisibility=hidden -CPP_GCC4_FLAGS = -fvisibility-inlines-hidden -CPP = gcc - -LINK = -lgcc -static-libgcc - -INCLUDE = -I. -I$(SMSDK)/public -I$(SMSDK)/public/sourcepawn - -CFLAGS += -D_GNU_SOURCE -Wall -Werror -Wno-uninitialized -Wno-unused-result -Wno-unused -Wno-switch -Wno-parentheses -Wno-format -DLINUX -DHAVE_STDINT_H -DAMX_ANSIONLY -DENABLE_BINRELOC -Dstricmp=strcasecmp -m32 -CPPFLAGS += -Wno-non-virtual-dtor -fno-exceptions -fno-rtti - -################################################ -### DO NOT EDIT BELOW HERE FOR MOST PROJECTS ### -################################################ - -ifeq "$(DEBUG)" "true" - BIN_DIR = Debug - CFLAGS += $(C_DEBUG_FLAGS) -else - BIN_DIR = Release - CFLAGS += $(C_OPT_FLAGS) -endif - -GCC_VERSION := $(shell $(CPP) -dumpversion >&1 | cut -b1) -ifeq "$(GCC_VERSION)" "4" - CFLAGS += $(C_GCC4_FLAGS) - CPPFLAGS += $(CPP_GCC4_FLAGS) -endif - -OBJ_LINUX := $(OBJECTS:%.c=$(BIN_DIR)/%.o) - -$(BIN_DIR)/%.o: %.c - $(CPP) $(INCLUDE) $(CFLAGS) -o $@ -c $< - -all: - mkdir -p $(BIN_DIR)/zlib - $(MAKE) -f Makefile compiler - -compiler: $(OBJ_LINUX) - $(CPP) $(INCLUDE) $(OBJ_LINUX) $(LINK) -m32 -ldl -lm -o $(BIN_DIR)/$(BINARY) - -debug: - $(MAKE) -f Makefile all DEBUG=true - -default: all - -clean: - rm -rf $(BIN_DIR)/*.o - rm -rf $(BIN_DIR)/zlib/*.o - rm -rf $(BIN_DIR)/$(BINARY) diff --git a/sourcepawn/compiler/amx.h b/sourcepawn/compiler/amx.h deleted file mode 100644 index c3dc6dd7..00000000 --- a/sourcepawn/compiler/amx.h +++ /dev/null @@ -1,634 +0,0 @@ -/* Pawn Abstract Machine (for the Pawn language) - * - * Copyright (c) ITB CompuPhase, 1997-2006 - * - * This software is provided "as-is", without any express or implied warranty. - * In no event will the authors be held liable for any damages arising from - * the use of this software. - * - * Permission is granted to anyone to use this software for any purpose, - * including commercial applications, and to alter it and redistribute it - * freely, subject to the following restrictions: - * - * 1. The origin of this software must not be misrepresented; you must not - * claim that you wrote the original software. If you use this software in - * a product, an acknowledgment in the product documentation would be - * appreciated but is not required. - * 2. Altered source versions must be plainly marked as such, and must not be - * misrepresented as being the original software. - * 3. This notice may not be removed or altered from any source distribution. - * - * Version: $Id$ - */ - -#ifndef AMX_H_INCLUDED -#define AMX_H_INCLUDED - -#include /* for size_t */ -#include - -#if defined FREEBSD && !defined __FreeBSD__ - #define __FreeBSD__ -#endif -#if defined LINUX || defined __FreeBSD__ || defined __OpenBSD__ - #include "sclinux.h" -#endif - -#if defined HAVE_STDINT_H -# include -# include -#endif - -#if defined __GNUC__ - #if !defined HAVE_STDINT_H - #define HAVE_STDINT_H - #endif -#elif !defined HAVE_STDINT_H - #if defined __LCC__ || defined __DMC__ || defined LINUX || (defined __WATCOMC__ && __WATCOMC__ >= 1200) - #if defined HAVE_INTTYPES_H - #include - #else - #include - #endif - #elif !defined __STDC_VERSION__ || __STDC_VERSION__ < 199901L - /* The ISO C99 defines the int16_t and int_32t types. If the compiler got - * here, these types are probably undefined. - */ - #if defined __MACH__ - #include - typedef unsigned short int uint16_t; - typedef unsigned long int uint32_t; - #elif defined __FreeBSD__ - #include - #else - typedef short int int16_t; - typedef unsigned short int uint16_t; - #if defined SN_TARGET_PS2 - typedef int int32_t; - typedef unsigned int uint32_t; - #else - typedef long int int32_t; - typedef unsigned long int uint32_t; - #endif - #if defined __WIN32__ || defined _WIN32 || defined WIN32 - typedef __int64 int64_t; - typedef unsigned __int64 uint64_t; - #define HAVE_I64 - #elif defined __GNUC__ - typedef long long int64_t; - typedef unsigned long long uint64_t; - #define HAVE_I64 - #endif - #endif - #endif - #define HAVE_STDINT_H -#endif -#if defined _LP64 || defined WIN64 || defined _WIN64 - #if !defined __64BIT__ - #define __64BIT__ - #endif -#endif - -#if HAVE_ALLOCA_H - #include -#endif -#if defined __WIN32__ || defined _WIN32 || defined WIN32 /* || defined __MSDOS__ */ - #if !defined alloca - #define alloca(n) _alloca(n) - #endif -#endif - -#if !defined arraysize - #define arraysize(array) (sizeof(array) / sizeof((array)[0])) -#endif -#if !defined assert_static - /* see "Compile-Time Assertions" by Ralf Holly, - * C/C++ Users Journal, November 2004 - */ - #define assert_static(e) \ - do { \ - enum { assert_static__ = 1/(e) }; \ - } while (0) -#endif - -#ifdef __cplusplus -extern "C" { -#endif - -#if defined PAWN_DLL - #if !defined AMX_NATIVE_CALL - #define AMX_NATIVE_CALL __stdcall - #endif - #if !defined AMXAPI - #define AMXAPI __stdcall - #endif -#endif - -/* calling convention for native functions */ -#if !defined AMX_NATIVE_CALL - #define AMX_NATIVE_CALL -#endif -/* calling convention for all interface functions and callback functions */ -#if !defined AMXAPI - #if defined STDECL - #define AMXAPI __stdcall - #elif defined CDECL - #define AMXAPI __cdecl - #elif defined GCC_HASCLASSVISIBILITY - #define AMXAPI __attribute__ ((visibility("default"))) - #else - #define AMXAPI - #endif -#endif -#if !defined AMXEXPORT - #define AMXEXPORT -#endif - -/* File format version (in CUR_FILE_VERSION) - * 0 (original version) - * 1 (opcodes JUMP.pri, SWITCH and CASETBL) - * 2 (compressed files) - * 3 (public variables) - * 4 (opcodes SWAP.pri/alt and PUSHADDR) - * 5 (tagnames table) - * 6 (reformatted header) - * 7 (name table, opcodes SYMTAG & SYSREQ.D) - * 8 (opcode STMT, renewed debug interface) - * 9 (macro opcodes) - * MIN_FILE_VERSION is the lowest file version number that the current AMX - * implementation supports. If the AMX file header gets new fields, this number - * often needs to be incremented. MAX_AMX_VERSION is the lowest AMX version that - * is needed to support the current file version. When there are new opcodes, - * this number needs to be incremented. - * The file version supported by the JIT may run behind MIN_AMX_VERSION. So - * there is an extra constant for it: MAX_FILE_VER_JIT. - */ -#define CUR_FILE_VERSION 9 /* current file version; also the current AMX version */ -#define MIN_FILE_VERSION 6 /* lowest supported file format version for the current AMX version */ -#define MIN_AMX_VERSION 9 /* minimum AMX version needed to support the current file format */ -#define MAX_FILE_VER_JIT 8 /* file version supported by the JIT */ -#define MIN_AMX_VER_JIT 8 /* AMX version supported by the JIT */ - -#if !defined PAWN_CELL_SIZE - #define PAWN_CELL_SIZE 32 /* by default, use 32-bit cells */ -#endif -#if PAWN_CELL_SIZE==16 - typedef uint16_t ucell; - typedef int16_t cell; -#elif PAWN_CELL_SIZE==32 - typedef uint32_t ucell; - typedef int32_t cell; -#elif PAWN_CELL_SIZE==64 - typedef uint64_t ucell; - typedef int64_t cell; -#else - #error Unsupported cell size (PAWN_CELL_SIZE) -#endif - -#define UNPACKEDMAX (((cell)1 << (sizeof(cell)-1)*8) - 1) -#define UNLIMITED (~1u >> 1) - -struct tagAMX; -typedef cell (AMX_NATIVE_CALL *AMX_NATIVE)(struct tagAMX *amx, cell *params); -typedef int (AMXAPI *AMX_CALLBACK)(struct tagAMX *amx, cell index, - cell *result, cell *params); -typedef int (AMXAPI *AMX_DEBUG)(struct tagAMX *amx); -typedef int (AMXAPI *AMX_IDLE)(struct tagAMX *amx, int AMXAPI Exec(struct tagAMX *, cell *, int)); -#if !defined _FAR - #define _FAR -#endif - -#if defined _MSC_VER - #pragma warning(disable:4103) /* disable warning message 4103 that complains - * about pragma pack in a header file */ - #pragma warning(disable:4100) /* "'%$S' : unreferenced formal parameter" */ -#endif - -/* Some compilers do not support the #pragma align, which should be fine. Some - * compilers give a warning on unknown #pragmas, which is not so fine... - */ -#if (defined SN_TARGET_PS2 || defined __GNUC__) && !defined AMX_NO_ALIGN - #define AMX_NO_ALIGN -#endif - -#if !defined AMX_NO_ALIGN - #if defined LINUX || defined __FreeBSD__ - #pragma pack(1) /* structures must be packed (byte-aligned) */ - #elif defined MACOS && defined __MWERKS__ - #pragma options align=mac68k - #else - #pragma pack(push) - #pragma pack(1) /* structures must be packed (byte-aligned) */ - #if defined __TURBOC__ - #pragma option -a- /* "pack" pragma for older Borland compilers */ - #endif - #endif -#endif - -typedef struct tagAMX_NATIVE_INFO { - const char _FAR *name; - AMX_NATIVE func; -} AMX_NATIVE_INFO; - -#define AMX_USERNUM 4 -#define sEXPMAX 19 /* maximum name length for file version <= 6 */ -#define sNAMEMAX 63 /* maximum name length of symbol name */ - -typedef struct tagAMX_FUNCSTUB { - ucell address; - char name[sEXPMAX+1]; -} AMX_FUNCSTUB; - -typedef struct tagFUNCSTUBNT { - ucell address; - uint32_t nameofs; -} AMX_FUNCSTUBNT; - -/* The AMX structure is the internal structure for many functions. Not all - * fields are valid at all times; many fields are cached in local variables. - */ -typedef struct tagAMX { - unsigned char _FAR *base; /* points to the AMX header plus the code, optionally also the data */ - unsigned char _FAR *data; /* points to separate data+stack+heap, may be NULL */ - AMX_CALLBACK callback; - AMX_DEBUG debug ; /* debug callback */ - /* for external functions a few registers must be accessible from the outside */ - cell cip ; /* instruction pointer: relative to base + amxhdr->cod */ - cell frm ; /* stack frame base: relative to base + amxhdr->dat */ - cell hea ; /* top of the heap: relative to base + amxhdr->dat */ - cell hlw ; /* bottom of the heap: relative to base + amxhdr->dat */ - cell stk ; /* stack pointer: relative to base + amxhdr->dat */ - cell stp ; /* top of the stack: relative to base + amxhdr->dat */ - int flags ; /* current status, see amx_Flags() */ - /* user data */ - long usertags[AMX_USERNUM] ; - void _FAR *userdata[AMX_USERNUM] ; - /* native functions can raise an error */ - int error ; - /* passing parameters requires a "count" field */ - int paramcount; - /* the sleep opcode needs to store the full AMX status */ - cell pri ; - cell alt ; - cell reset_stk ; - cell reset_hea ; - /* extra fields for increased performance */ - cell sysreq_d ; /* relocated address/value for the SYSREQ.D opcode */ - #if defined JIT - /* support variables for the JIT */ - int reloc_size ; /* required temporary buffer for relocations */ - long code_size ; /* estimated memory footprint of the native code */ - #endif -} AMX; - -/* The AMX_HEADER structure is both the memory format as the file format. The - * structure is used internaly. - */ -typedef struct tagAMX_HEADER { - int32_t size ; /* size of the "file" */ - uint16_t magic ; /* signature */ - char file_version ; /* file format version */ - char amx_version ; /* required version of the AMX */ - int16_t flags ; - int16_t defsize ; /* size of a definition record */ - int32_t cod ; /* initial value of COD - code block */ - int32_t dat ; /* initial value of DAT - data block */ - int32_t hea ; /* initial value of HEA - start of the heap */ - int32_t stp ; /* initial value of STP - stack top */ - int32_t cip ; /* initial value of CIP - the instruction pointer */ - int32_t publics ; /* offset to the "public functions" table */ - int32_t natives ; /* offset to the "native functions" table */ - int32_t libraries ; /* offset to the table of libraries */ - int32_t pubvars ; /* the "public variables" table */ - int32_t tags ; /* the "public tagnames" table */ - int32_t nametable ; /* name table */ -} AMX_HEADER; - -#if PAWN_CELL_SIZE==16 - #define AMX_MAGIC 0xf1e2 -#elif PAWN_CELL_SIZE==32 - #define AMX_MAGIC 0xf1e0 -#elif PAWN_CELL_SIZE==64 - #define AMX_MAGIC 0xf1e1 -#endif - -enum { - AMX_ERR_NONE, - /* reserve the first 15 error codes for exit codes of the abstract machine */ - AMX_ERR_EXIT, /* forced exit */ - AMX_ERR_ASSERT, /* assertion failed */ - AMX_ERR_STACKERR, /* stack/heap collision */ - AMX_ERR_BOUNDS, /* index out of bounds */ - AMX_ERR_MEMACCESS, /* invalid memory access */ - AMX_ERR_INVINSTR, /* invalid instruction */ - AMX_ERR_STACKLOW, /* stack underflow */ - AMX_ERR_HEAPLOW, /* heap underflow */ - AMX_ERR_CALLBACK, /* no callback, or invalid callback */ - AMX_ERR_NATIVE, /* native function failed */ - AMX_ERR_DIVIDE, /* divide by zero */ - AMX_ERR_SLEEP, /* go into sleepmode - code can be restarted */ - AMX_ERR_INVSTATE, /* invalid state for this access */ - - AMX_ERR_MEMORY = 16, /* out of memory */ - AMX_ERR_FORMAT, /* invalid file format */ - AMX_ERR_VERSION, /* file is for a newer version of the AMX */ - AMX_ERR_NOTFOUND, /* function not found */ - AMX_ERR_INDEX, /* invalid index parameter (bad entry point) */ - AMX_ERR_DEBUG, /* debugger cannot run */ - AMX_ERR_INIT, /* AMX not initialized (or doubly initialized) */ - AMX_ERR_USERDATA, /* unable to set user data field (table full) */ - AMX_ERR_INIT_JIT, /* cannot initialize the JIT */ - AMX_ERR_PARAMS, /* parameter error */ - AMX_ERR_DOMAIN, /* domain error, expression result does not fit in range */ - AMX_ERR_GENERAL, /* general error (unknown or unspecific error) */ -}; - -/* AMX_FLAG_CHAR16 0x01 no longer used */ -#define AMX_FLAG_DEBUG 0x02 /* symbolic info. available */ -#define AMX_FLAG_COMPACT 0x04 /* compact encoding */ -#define AMX_FLAG_SLEEP 0x08 /* script uses the sleep instruction (possible re-entry or power-down mode) */ -#define AMX_FLAG_NOCHECKS 0x10 /* no array bounds checking; no BREAK opcodes */ -#define AMX_FLAG_SYSREQN 0x800 /* script new (optimized) version of SYSREQ opcode */ -#define AMX_FLAG_NTVREG 0x1000 /* all native functions are registered */ -#define AMX_FLAG_JITC 0x2000 /* abstract machine is JIT compiled */ -#define AMX_FLAG_BROWSE 0x4000 /* busy browsing */ -#define AMX_FLAG_RELOC 0x8000 /* jump/call addresses relocated */ - -#define AMX_EXEC_MAIN (-1) /* start at program entry point */ -#define AMX_EXEC_CONT (-2) /* continue from last address */ - -#define AMX_USERTAG(a,b,c,d) ((a) | ((b)<<8) | ((long)(c)<<16) | ((long)(d)<<24)) - -#if !defined AMX_COMPACTMARGIN - #define AMX_COMPACTMARGIN 64 -#endif - -/* for native functions that use floating point parameters, the following - * two macros are convenient for casting a "cell" into a "float" type _without_ - * changing the bit pattern - */ -#if PAWN_CELL_SIZE==32 - #define amx_ftoc(f) ( * ((cell*)&f) ) /* float to cell */ - #define amx_ctof(c) ( * ((float*)&c) ) /* cell to float */ -#elif PAWN_CELL_SIZE==64 - #define amx_ftoc(f) ( * ((cell*)&f) ) /* float to cell */ - #define amx_ctof(c) ( * ((double*)&c) ) /* cell to float */ -#else - #error Unsupported cell size -#endif - -#define amx_StrParam(amx,param,result) \ - do { \ - cell *amx_cstr_; int amx_length_; \ - amx_GetAddr((amx), (param), &amx_cstr_); \ - amx_StrLen(amx_cstr_, &amx_length_); \ - if (amx_length_ > 0 && \ - ((result) = (void*)alloca((amx_length_ + 1) * sizeof(*(result)))) != NULL) \ - amx_GetString((char*)(result), amx_cstr_, sizeof(*(result))>1, amx_length_ + 1); \ - else (result) = NULL; \ - } while (0) - -uint16_t * AMXAPI amx_Align16(uint16_t *v); -uint32_t * AMXAPI amx_Align32(uint32_t *v); -#if defined _I64_MAX || defined HAVE_I64 - uint64_t * AMXAPI amx_Align64(uint64_t *v); -#endif -int AMXAPI amx_Allot(AMX *amx, int cells, cell *amx_addr, cell **phys_addr); -int AMXAPI amx_Callback(AMX *amx, cell index, cell *result, cell *params); -int AMXAPI amx_Cleanup(AMX *amx); -int AMXAPI amx_Clone(AMX *amxClone, AMX *amxSource, void *data); -int AMXAPI amx_Exec(AMX *amx, cell *retval, int index); -int AMXAPI amx_FindNative(AMX *amx, const char *name, int *index); -int AMXAPI amx_FindPublic(AMX *amx, const char *funcname, int *index); -int AMXAPI amx_FindPubVar(AMX *amx, const char *varname, cell *amx_addr); -int AMXAPI amx_FindTagId(AMX *amx, cell tag_id, char *tagname); -int AMXAPI amx_Flags(AMX *amx,uint16_t *flags); -int AMXAPI amx_GetAddr(AMX *amx,cell amx_addr,cell **phys_addr); -int AMXAPI amx_GetNative(AMX *amx, int index, char *funcname); -int AMXAPI amx_GetPublic(AMX *amx, int index, char *funcname); -int AMXAPI amx_GetPubVar(AMX *amx, int index, char *varname, cell *amx_addr); -int AMXAPI amx_GetString(char *dest,const cell *source, int use_wchar, size_t size); -int AMXAPI amx_GetTag(AMX *amx, int index, char *tagname, cell *tag_id); -int AMXAPI amx_GetUserData(AMX *amx, long tag, void **ptr); -int AMXAPI amx_Init(AMX *amx, void *program); -int AMXAPI amx_InitJIT(AMX *amx, void *reloc_table, void *native_code); -int AMXAPI amx_MemInfo(AMX *amx, long *codesize, long *datasize, long *stackheap); -int AMXAPI amx_NameLength(AMX *amx, int *length); -AMX_NATIVE_INFO * AMXAPI amx_NativeInfo(const char *name, AMX_NATIVE func); -int AMXAPI amx_NumNatives(AMX *amx, int *number); -int AMXAPI amx_NumPublics(AMX *amx, int *number); -int AMXAPI amx_NumPubVars(AMX *amx, int *number); -int AMXAPI amx_NumTags(AMX *amx, int *number); -int AMXAPI amx_Push(AMX *amx, cell value); -int AMXAPI amx_PushArray(AMX *amx, cell *amx_addr, cell **phys_addr, const cell array[], int numcells); -int AMXAPI amx_PushString(AMX *amx, cell *amx_addr, cell **phys_addr, const char *string, int pack, int use_wchar); -int AMXAPI amx_RaiseError(AMX *amx, int error); -int AMXAPI amx_Register(AMX *amx, const AMX_NATIVE_INFO *nativelist, int number); -int AMXAPI amx_Release(AMX *amx, cell amx_addr); -int AMXAPI amx_SetCallback(AMX *amx, AMX_CALLBACK callback); -int AMXAPI amx_SetDebugHook(AMX *amx, AMX_DEBUG debug); -int AMXAPI amx_SetString(cell *dest, const char *source, int pack, int use_wchar, size_t size); -int AMXAPI amx_SetUserData(AMX *amx, long tag, void *ptr); -int AMXAPI amx_StrLen(const cell *cstring, int *length); -int AMXAPI amx_UTF8Check(const char *string, int *length); -int AMXAPI amx_UTF8Get(const char *string, const char **endptr, cell *value); -int AMXAPI amx_UTF8Len(const cell *cstr, int *length); -int AMXAPI amx_UTF8Put(char *string, char **endptr, int maxchars, cell value); - -#if PAWN_CELL_SIZE==16 - #define amx_AlignCell(v) amx_Align16(v) -#elif PAWN_CELL_SIZE==32 - #define amx_AlignCell(v) amx_Align32(v) -#elif PAWN_CELL_SIZE==64 && (defined _I64_MAX || defined HAVE_I64) - #define amx_AlignCell(v) amx_Align64(v) -#else - #error Unsupported cell size -#endif - -#define amx_RegisterFunc(amx, name, func) \ - amx_Register((amx), amx_NativeInfo((name),(func)), 1); - -#if !defined AMX_NO_ALIGN - #if defined LINUX || defined __FreeBSD__ - #pragma pack() /* reset default packing */ - #elif defined MACOS && defined __MWERKS__ - #pragma options align=reset - #else - #pragma pack(pop) /* reset previous packing */ - #endif -#endif - -#ifdef __cplusplus -} -#endif - -typedef enum { - OP_NONE, /* invalid opcode */ - OP_LOAD_PRI, - OP_LOAD_ALT, - OP_LOAD_S_PRI, - OP_LOAD_S_ALT, - OP_LREF_PRI, - OP_LREF_ALT, - OP_LREF_S_PRI, - OP_LREF_S_ALT, - OP_LOAD_I, - OP_LODB_I, - OP_CONST_PRI, - OP_CONST_ALT, - OP_ADDR_PRI, - OP_ADDR_ALT, - OP_STOR_PRI, - OP_STOR_ALT, - OP_STOR_S_PRI, - OP_STOR_S_ALT, - OP_SREF_PRI, - OP_SREF_ALT, - OP_SREF_S_PRI, - OP_SREF_S_ALT, - OP_STOR_I, - OP_STRB_I, - OP_LIDX, - OP_LIDX_B, - OP_IDXADDR, - OP_IDXADDR_B, - OP_ALIGN_PRI, - OP_ALIGN_ALT, - OP_LCTRL, - OP_SCTRL, - OP_MOVE_PRI, - OP_MOVE_ALT, - OP_XCHG, - OP_PUSH_PRI, - OP_PUSH_ALT, - OP_PUSH_R, - OP_PUSH_C, - OP_PUSH, - OP_PUSH_S, - OP_POP_PRI, - OP_POP_ALT, - OP_STACK, - OP_HEAP, - OP_PROC, - OP_RET, - OP_RETN, - OP_CALL, - OP_CALL_PRI, - OP_JUMP, - OP_JREL, - OP_JZER, - OP_JNZ, - OP_JEQ, - OP_JNEQ, - OP_JLESS, - OP_JLEQ, - OP_JGRTR, - OP_JGEQ, - OP_JSLESS, - OP_JSLEQ, - OP_JSGRTR, - OP_JSGEQ, - OP_SHL, - OP_SHR, - OP_SSHR, - OP_SHL_C_PRI, - OP_SHL_C_ALT, - OP_SHR_C_PRI, - OP_SHR_C_ALT, - OP_SMUL, - OP_SDIV, - OP_SDIV_ALT, - OP_UMUL, - OP_UDIV, - OP_UDIV_ALT, - OP_ADD, - OP_SUB, - OP_SUB_ALT, - OP_AND, - OP_OR, - OP_XOR, - OP_NOT, - OP_NEG, - OP_INVERT, - OP_ADD_C, - OP_SMUL_C, - OP_ZERO_PRI, - OP_ZERO_ALT, - OP_ZERO, - OP_ZERO_S, - OP_SIGN_PRI, - OP_SIGN_ALT, - OP_EQ, - OP_NEQ, - OP_LESS, - OP_LEQ, - OP_GRTR, - OP_GEQ, - OP_SLESS, - OP_SLEQ, - OP_SGRTR, - OP_SGEQ, - OP_EQ_C_PRI, - OP_EQ_C_ALT, - OP_INC_PRI, - OP_INC_ALT, - OP_INC, - OP_INC_S, - OP_INC_I, - OP_DEC_PRI, - OP_DEC_ALT, - OP_DEC, - OP_DEC_S, - OP_DEC_I, - OP_MOVS, - OP_CMPS, - OP_FILL, - OP_HALT, - OP_BOUNDS, - OP_SYSREQ_PRI, - OP_SYSREQ_C, - OP_FILE, /* obsolete */ - OP_LINE, /* obsolete */ - OP_SYMBOL, /* obsolete */ - OP_SRANGE, /* obsolete */ - OP_JUMP_PRI, - OP_SWITCH, - OP_CASETBL, - OP_SWAP_PRI, - OP_SWAP_ALT, - OP_PUSH_ADR, - OP_NOP, - OP_SYSREQ_N, - OP_SYMTAG, /* obsolete */ - OP_BREAK, - OP_PUSH2_C, - OP_PUSH2, - OP_PUSH2_S, - OP_PUSH2_ADR, - OP_PUSH3_C, - OP_PUSH3, - OP_PUSH3_S, - OP_PUSH3_ADR, - OP_PUSH4_C, - OP_PUSH4, - OP_PUSH4_S, - OP_PUSH4_ADR, - OP_PUSH5_C, - OP_PUSH5, - OP_PUSH5_S, - OP_PUSH5_ADR, - OP_LOAD_BOTH, - OP_LOAD_S_BOTH, - OP_CONST, - OP_CONST_S, - /* ----- */ - OP_SYSREQ_D, - OP_SYSREQ_ND, - /* ----- */ - OP_HEAP_I, - OP_PUSH_H_C, - OP_GENARRAY, - OP_NUM_OPCODES -} OPCODE; - -#endif /* AMX_H_INCLUDED */ diff --git a/sourcepawn/compiler/amxdbg.h b/sourcepawn/compiler/amxdbg.h deleted file mode 100644 index 5726d78b..00000000 --- a/sourcepawn/compiler/amxdbg.h +++ /dev/null @@ -1,173 +0,0 @@ -/* Abstract Machine for the Pawn compiler, debugger support - * - * This file contains extra definitions that are convenient for debugger - * support. - * - * Copyright (c) ITB CompuPhase, 2005 - * - * This software is provided "as-is", without any express or implied warranty. - * In no event will the authors be held liable for any damages arising from - * the use of this software. - * - * Permission is granted to anyone to use this software for any purpose, - * including commercial applications, and to alter it and redistribute it - * freely, subject to the following restrictions: - * - * 1. The origin of this software must not be misrepresented; you must not - * claim that you wrote the original software. If you use this software in - * a product, an acknowledgment in the product documentation would be - * appreciated but is not required. - * 2. Altered source versions must be plainly marked as such, and must not be - * misrepresented as being the original software. - * 3. This notice may not be removed or altered from any source distribution. - * - * Version: $Id$ - */ - -#ifndef AMXDBG_H_INCLUDED -#define AMXDBG_H_INCLUDED - -#ifndef AMX_H_INCLUDED - #include "amx.h" -#endif - -#ifdef __cplusplus -extern "C" { -#endif - -/* Some compilers do not support the #pragma align, which should be fine. Some - * compilers give a warning on unknown #pragmas, which is not so fine... - */ -#if defined SN_TARGET_PS2 || defined __GNUC__ - #define AMX_NO_ALIGN -#endif - -#if defined __GNUC__ - #define PACKED __attribute__((packed)) -#else - #define PACKED -#endif - -#if !defined AMX_NO_ALIGN - #if defined LINUX || defined __FreeBSD__ - #pragma pack(1) /* structures must be packed (byte-aligned) */ - #elif defined MACOS && defined __MWERKS__ - #pragma options align=mac68k - #else - #pragma pack(push) - #pragma pack(1) /* structures must be packed (byte-aligned) */ - #if defined __TURBOC__ - #pragma option -a- /* "pack" pragma for older Borland compilers */ - #endif - #endif -#endif - -typedef struct tagAMX_DBG_HDR { - int32_t size PACKED; /* size of the debug information chunk */ - uint16_t magic PACKED; /* signature, must be 0xf1ef */ - char file_version; /* file format version */ - char amx_version; /* required version of the AMX */ - int16_t flags PACKED; /* currently unused */ - int16_t files PACKED; /* number of entries in the "file" table */ - int32_t lines PACKED; /* number of entries in the "line" table */ - int32_t symbols PACKED; /* number of entries in the "symbol" table */ - int16_t tags PACKED; /* number of entries in the "tag" table */ - int16_t automatons PACKED; /* number of entries in the "automaton" table */ - int16_t states PACKED; /* number of entries in the "state" table */ -} PACKED AMX_DBG_HDR; -#define AMX_DBG_MAGIC 0xf1ef - -typedef struct tagAMX_DBG_FILE { - ucell address PACKED; /* address in the code segment where generated code (for this file) starts */ - char name[1]; /* ASCII string, zero-terminated */ -} PACKED AMX_DBG_FILE; - -typedef struct tagAMX_DBG_LINE { - ucell address PACKED; /* address in the code segment where generated code (for this line) starts */ - int32_t line PACKED; /* line number */ -} PACKED AMX_DBG_LINE; - -typedef struct tagAMX_DBG_SYMBOL { - ucell address PACKED; /* address in the data segment or relative to the frame */ - int16_t tag PACKED; /* tag for the symbol */ - ucell codestart PACKED; /* address in the code segment from which this symbol is valid (in scope) */ - ucell codeend PACKED; /* address in the code segment until which this symbol is valid (in scope) */ - char ident; /* kind of symbol (function/variable) */ - char vclass; /* class of symbol (global/local) */ - int16_t dim PACKED; /* number of dimensions */ - char name[1]; /* ASCII string, zero-terminated */ -} PACKED AMX_DBG_SYMBOL; - -typedef struct tagAMX_DBG_SYMDIM { - int16_t tag PACKED; /* tag for the array dimension */ - ucell size PACKED; /* size of the array dimension */ -} PACKED AMX_DBG_SYMDIM; - -typedef struct tagAMX_DBG_TAG { - int16_t tag PACKED; /* tag id */ - char name[1]; /* ASCII string, zero-terminated */ -} PACKED AMX_DBG_TAG; - -typedef struct tagAMX_DBG_MACHINE { - int16_t automaton PACKED; /* automaton id */ - ucell address PACKED; /* address of state variable */ - char name[1]; /* ASCII string, zero-terminated */ -} PACKED AMX_DBG_MACHINE; - -typedef struct tagAMX_DBG_STATE { - int16_t state PACKED; /* state id */ - int16_t automaton PACKED; /* automaton id */ - char name[1]; /* ASCII string, zero-terminated */ -} PACKED AMX_DBG_STATE; - -typedef struct tagAMX_DBG { - AMX_DBG_HDR _FAR *hdr PACKED; /* points to the AMX_DBG header */ - AMX_DBG_FILE _FAR **filetbl PACKED; - AMX_DBG_LINE _FAR *linetbl PACKED; - AMX_DBG_SYMBOL _FAR **symboltbl PACKED; - AMX_DBG_TAG _FAR **tagtbl PACKED; - AMX_DBG_MACHINE _FAR **automatontbl PACKED; - AMX_DBG_STATE _FAR **statetbl PACKED; -} PACKED AMX_DBG; - -#if !defined iVARIABLE - #define iVARIABLE 1 /* cell that has an address and that can be fetched directly (lvalue) */ - #define iREFERENCE 2 /* iVARIABLE, but must be dereferenced */ - #define iARRAY 3 - #define iREFARRAY 4 /* an array passed by reference (i.e. a pointer) */ - #define iFUNCTN 9 -#endif - - -int AMXAPI dbg_FreeInfo(AMX_DBG *amxdbg); -int AMXAPI dbg_LoadInfo(AMX_DBG *amxdbg, void *dbg_addr); - -int AMXAPI dbg_LookupFile(AMX_DBG *amxdbg, ucell address, const char **filename); -int AMXAPI dbg_LookupFunction(AMX_DBG *amxdbg, ucell address, const char **funcname); -int AMXAPI dbg_LookupLine(AMX_DBG *amxdbg, ucell address, long *line); - -int AMXAPI dbg_GetFunctionAddress(AMX_DBG *amxdbg, const char *funcname, const char *filename, ucell *address); -int AMXAPI dbg_GetLineAddress(AMX_DBG *amxdbg, long line, const char *filename, ucell *address); -int AMXAPI dbg_GetAutomatonName(AMX_DBG *amxdbg, int automaton, const char **name); -int AMXAPI dbg_GetStateName(AMX_DBG *amxdbg, int state, const char **name); -int AMXAPI dbg_GetTagName(AMX_DBG *amxdbg, int tag, const char **name); -int AMXAPI dbg_GetVariable(AMX_DBG *amxdbg, const char *symname, ucell scopeaddr, const AMX_DBG_SYMBOL **sym); -int AMXAPI dbg_GetArrayDim(AMX_DBG *amxdbg, const AMX_DBG_SYMBOL *sym, const AMX_DBG_SYMDIM **symdim); - - -#if !defined AMX_NO_ALIGN - #if defined LINUX || defined __FreeBSD__ - #pragma pack() /* reset default packing */ - #elif defined MACOS && defined __MWERKS__ - #pragma options align=reset - #else - #pragma pack(pop) /* reset previous packing */ - #endif -#endif - -#ifdef __cplusplus -} -#endif - -#endif /* AMXDBG_H_INCLUDED */ - diff --git a/sourcepawn/compiler/binreloc.c b/sourcepawn/compiler/binreloc.c deleted file mode 100644 index c6dc0ae7..00000000 --- a/sourcepawn/compiler/binreloc.c +++ /dev/null @@ -1,766 +0,0 @@ -/* - * BinReloc - a library for creating relocatable executables - * Written by: Hongli Lai - * http://autopackage.org/ - * - * This source code is public domain. You can relicense this code - * under whatever license you want. - * - * See http://autopackage.org/docs/binreloc/ for - * more information and how to use this. - */ - -#ifndef __BINRELOC_C__ -#define __BINRELOC_C__ - -#ifdef ENABLE_BINRELOC - #include - #include - #include -#endif /* ENABLE_BINRELOC */ -#include -#include -#include -#include -#include "binreloc.h" - -#ifdef __cplusplus -extern "C" { -#endif /* __cplusplus */ - - - -/** @internal - * Find the canonical filename of the executable. Returns the filename - * (which must be freed) or NULL on error. If the parameter 'error' is - * not NULL, the error code will be stored there, if an error occured. - */ -static char * -_br_find_exe (BrInitError *error) -{ -#ifndef ENABLE_BINRELOC - if (error) - *error = BR_INIT_ERROR_DISABLED; - return NULL; -#else - char *path, *path2, *line, *result; - size_t buf_size; - ssize_t size; - struct stat stat_buf; - FILE *f; - - /* Read from /proc/self/exe (symlink) */ - if (sizeof (path) > SSIZE_MAX) - buf_size = SSIZE_MAX - 1; - else - buf_size = PATH_MAX - 1; - path = (char *) malloc (buf_size); - if (path == NULL) { - /* Cannot allocate memory. */ - if (error) - *error = BR_INIT_ERROR_NOMEM; - return NULL; - } - path2 = (char *) malloc (buf_size); - if (path2 == NULL) { - /* Cannot allocate memory. */ - if (error) - *error = BR_INIT_ERROR_NOMEM; - free (path); - return NULL; - } - - strncpy (path2, "/proc/self/exe", buf_size - 1); - - while (1) { - int i; - - size = readlink (path2, path, buf_size - 1); - if (size == -1) { - /* Error. */ - free (path2); - break; - } - - /* readlink() success. */ - path[size] = '\0'; - - /* Check whether the symlink's target is also a symlink. - * We want to get the final target. */ - i = stat (path, &stat_buf); - if (i == -1) { - /* Error. */ - free (path2); - break; - } - - /* stat() success. */ - if (!S_ISLNK (stat_buf.st_mode)) { - /* path is not a symlink. Done. */ - free (path2); - return path; - } - - /* path is a symlink. Continue loop and resolve this. */ - strncpy (path, path2, buf_size - 1); - } - - - /* readlink() or stat() failed; this can happen when the program is - * running in Valgrind 2.2. Read from /proc/self/maps as fallback. */ - - buf_size = PATH_MAX + 128; - line = (char *) realloc (path, buf_size); - if (line == NULL) { - /* Cannot allocate memory. */ - free (path); - if (error) - *error = BR_INIT_ERROR_NOMEM; - return NULL; - } - - f = fopen ("/proc/self/maps", "r"); - if (f == NULL) { - free (line); - if (error) - *error = BR_INIT_ERROR_OPEN_MAPS; - return NULL; - } - - /* The first entry should be the executable name. */ - result = fgets (line, (int) buf_size, f); - if (result == NULL) { - fclose (f); - free (line); - if (error) - *error = BR_INIT_ERROR_READ_MAPS; - return NULL; - } - - /* Get rid of newline character. */ - buf_size = strlen (line); - if (buf_size <= 0) { - /* Huh? An empty string? */ - fclose (f); - free (line); - if (error) - *error = BR_INIT_ERROR_INVALID_MAPS; - return NULL; - } - if (line[buf_size - 1] == 10) - line[buf_size - 1] = 0; - - /* Extract the filename; it is always an absolute path. */ - path = strchr (line, '/'); - - /* Sanity check. */ - if (strstr (line, " r-xp ") == NULL || path == NULL) { - fclose (f); - free (line); - if (error) - *error = BR_INIT_ERROR_INVALID_MAPS; - return NULL; - } - - path = strdup (path); - free (line); - fclose (f); - return path; -#endif /* ENABLE_BINRELOC */ -} - - -/** @internal - * Find the canonical filename of the executable which owns symbol. - * Returns a filename which must be freed, or NULL on error. - */ -static char * -_br_find_exe_for_symbol (const void *symbol, BrInitError *error) -{ -#ifndef ENABLE_BINRELOC - if (error) - *error = BR_INIT_ERROR_DISABLED; - return (char *) NULL; -#else - #define SIZE PATH_MAX + 100 - FILE *f; - size_t address_string_len; - char *address_string, line[SIZE], *found; - - if (symbol == NULL) - return (char *) NULL; - - f = fopen ("/proc/self/maps", "r"); - if (f == NULL) - return (char *) NULL; - - address_string_len = 4; - address_string = (char *) malloc (address_string_len); - found = (char *) NULL; - - while (!feof (f)) { - char *start_addr, *end_addr, *end_addr_end, *file; - void *start_addr_p, *end_addr_p; - size_t len; - - if (fgets (line, SIZE, f) == NULL) - break; - - /* Sanity check. */ - if (strstr (line, " r-xp ") == NULL || strchr (line, '/') == NULL) - continue; - - /* Parse line. */ - start_addr = line; - end_addr = strchr (line, '-'); - file = strchr (line, '/'); - - /* More sanity check. */ - if (!(file > end_addr && end_addr != NULL && end_addr[0] == '-')) - continue; - - end_addr[0] = '\0'; - end_addr++; - end_addr_end = strchr (end_addr, ' '); - if (end_addr_end == NULL) - continue; - - end_addr_end[0] = '\0'; - len = strlen (file); - if (len == 0) - continue; - if (file[len - 1] == '\n') - file[len - 1] = '\0'; - - /* Get rid of "(deleted)" from the filename. */ - len = strlen (file); - if (len > 10 && strcmp (file + len - 10, " (deleted)") == 0) - file[len - 10] = '\0'; - - /* I don't know whether this can happen but better safe than sorry. */ - len = strlen (start_addr); - if (len != strlen (end_addr)) - continue; - - - /* Transform the addresses into a string in the form of 0xdeadbeef, - * then transform that into a pointer. */ - if (address_string_len < len + 3) { - address_string_len = len + 3; - address_string = (char *) realloc (address_string, address_string_len); - } - - memcpy (address_string, "0x", 2); - memcpy (address_string + 2, start_addr, len); - address_string[2 + len] = '\0'; - sscanf (address_string, "%p", &start_addr_p); - - memcpy (address_string, "0x", 2); - memcpy (address_string + 2, end_addr, len); - address_string[2 + len] = '\0'; - sscanf (address_string, "%p", &end_addr_p); - - - if (symbol >= start_addr_p && symbol < end_addr_p) { - found = file; - break; - } - } - - free (address_string); - fclose (f); - - if (found == NULL) - return (char *) NULL; - else - return strdup (found); -#endif /* ENABLE_BINRELOC */ -} - - -#ifndef BINRELOC_RUNNING_DOXYGEN - #undef NULL - #define NULL ((void *) 0) /* typecasted as char* for C++ type safeness */ -#endif - -static char *exe = (char *) NULL; - - -/** Initialize the BinReloc library (for applications). - * - * This function must be called before using any other BinReloc functions. - * It attempts to locate the application's canonical filename. - * - * @note If you want to use BinReloc for a library, then you should call - * br_init_lib() instead. - * - * @param error If BinReloc failed to initialize, then the error code will - * be stored in this variable. Set to NULL if you want to - * ignore this. See #BrInitError for a list of error codes. - * - * @returns 1 on success, 0 if BinReloc failed to initialize. - */ -int -br_init (BrInitError *error) -{ - exe = _br_find_exe (error); - return exe != NULL; -} - - -/** Initialize the BinReloc library (for libraries). - * - * This function must be called before using any other BinReloc functions. - * It attempts to locate the calling library's canonical filename. - * - * @note The BinReloc source code MUST be included in your library, or this - * function won't work correctly. - * - * @param error If BinReloc failed to initialize, then the error code will - * be stored in this variable. Set to NULL if you want to - * ignore this. See #BrInitError for a list of error codes. - * - * @returns 1 on success, 0 if a filename cannot be found. - */ -int -br_init_lib (BrInitError *error) -{ - exe = _br_find_exe_for_symbol ((const void *) "", error); - return exe != NULL; -} - - -/** Find the canonical filename of the current application. - * - * @param default_exe A default filename which will be used as fallback. - * @returns A string containing the application's canonical filename, - * which must be freed when no longer necessary. If BinReloc is - * not initialized, or if br_init() failed, then a copy of - * default_exe will be returned. If default_exe is NULL, then - * NULL will be returned. - */ -char * -br_find_exe (const char *default_exe) -{ - if (exe == (char *) NULL) { - /* BinReloc is not initialized. */ - if (default_exe != (const char *) NULL) - return strdup (default_exe); - else - return (char *) NULL; - } - return strdup (exe); -} - - -/** Locate the directory in which the current application is installed. - * - * The prefix is generated by the following pseudo-code evaluation: - * \code - * dirname(exename) - * \endcode - * - * @param default_dir A default directory which will used as fallback. - * @return A string containing the directory, which must be freed when no - * longer necessary. If BinReloc is not initialized, or if the - * initialization function failed, then a copy of default_dir - * will be returned. If default_dir is NULL, then NULL will be - * returned. - */ -char * -br_find_exe_dir (const char *default_dir) -{ - if (exe == NULL) { - /* BinReloc not initialized. */ - if (default_dir != NULL) - return strdup (default_dir); - else - return NULL; - } - - return br_dirname (exe); -} - - -/** Locate the prefix in which the current application is installed. - * - * The prefix is generated by the following pseudo-code evaluation: - * \code - * dirname(dirname(exename)) - * \endcode - * - * @param default_prefix A default prefix which will used as fallback. - * @return A string containing the prefix, which must be freed when no - * longer necessary. If BinReloc is not initialized, or if - * the initialization function failed, then a copy of default_prefix - * will be returned. If default_prefix is NULL, then NULL will be returned. - */ -char * -br_find_prefix (const char *default_prefix) -{ - char *dir1, *dir2; - - if (exe == (char *) NULL) { - /* BinReloc not initialized. */ - if (default_prefix != (const char *) NULL) - return strdup (default_prefix); - else - return (char *) NULL; - } - - dir1 = br_dirname (exe); - dir2 = br_dirname (dir1); - free (dir1); - return dir2; -} - - -/** Locate the application's binary folder. - * - * The path is generated by the following pseudo-code evaluation: - * \code - * prefix + "/bin" - * \endcode - * - * @param default_bin_dir A default path which will used as fallback. - * @return A string containing the bin folder's path, which must be freed when - * no longer necessary. If BinReloc is not initialized, or if - * the initialization function failed, then a copy of default_bin_dir will - * be returned. If default_bin_dir is NULL, then NULL will be returned. - */ -char * -br_find_bin_dir (const char *default_bin_dir) -{ - char *prefix, *dir; - - prefix = br_find_prefix ((const char *) NULL); - if (prefix == (char *) NULL) { - /* BinReloc not initialized. */ - if (default_bin_dir != (const char *) NULL) - return strdup (default_bin_dir); - else - return (char *) NULL; - } - - dir = br_build_path (prefix, "bin"); - free (prefix); - return dir; -} - - -/** Locate the application's superuser binary folder. - * - * The path is generated by the following pseudo-code evaluation: - * \code - * prefix + "/sbin" - * \endcode - * - * @param default_sbin_dir A default path which will used as fallback. - * @return A string containing the sbin folder's path, which must be freed when - * no longer necessary. If BinReloc is not initialized, or if the - * initialization function failed, then a copy of default_sbin_dir will - * be returned. If default_bin_dir is NULL, then NULL will be returned. - */ -char * -br_find_sbin_dir (const char *default_sbin_dir) -{ - char *prefix, *dir; - - prefix = br_find_prefix ((const char *) NULL); - if (prefix == (char *) NULL) { - /* BinReloc not initialized. */ - if (default_sbin_dir != (const char *) NULL) - return strdup (default_sbin_dir); - else - return (char *) NULL; - } - - dir = br_build_path (prefix, "sbin"); - free (prefix); - return dir; -} - - -/** Locate the application's data folder. - * - * The path is generated by the following pseudo-code evaluation: - * \code - * prefix + "/share" - * \endcode - * - * @param default_data_dir A default path which will used as fallback. - * @return A string containing the data folder's path, which must be freed when - * no longer necessary. If BinReloc is not initialized, or if the - * initialization function failed, then a copy of default_data_dir - * will be returned. If default_data_dir is NULL, then NULL will be - * returned. - */ -char * -br_find_data_dir (const char *default_data_dir) -{ - char *prefix, *dir; - - prefix = br_find_prefix ((const char *) NULL); - if (prefix == (char *) NULL) { - /* BinReloc not initialized. */ - if (default_data_dir != (const char *) NULL) - return strdup (default_data_dir); - else - return (char *) NULL; - } - - dir = br_build_path (prefix, "share"); - free (prefix); - return dir; -} - - -/** Locate the application's localization folder. - * - * The path is generated by the following pseudo-code evaluation: - * \code - * prefix + "/share/locale" - * \endcode - * - * @param default_locale_dir A default path which will used as fallback. - * @return A string containing the localization folder's path, which must be freed when - * no longer necessary. If BinReloc is not initialized, or if the - * initialization function failed, then a copy of default_locale_dir will be returned. - * If default_locale_dir is NULL, then NULL will be returned. - */ -char * -br_find_locale_dir (const char *default_locale_dir) -{ - char *data_dir, *dir; - - data_dir = br_find_data_dir ((const char *) NULL); - if (data_dir == (char *) NULL) { - /* BinReloc not initialized. */ - if (default_locale_dir != (const char *) NULL) - return strdup (default_locale_dir); - else - return (char *) NULL; - } - - dir = br_build_path (data_dir, "locale"); - free (data_dir); - return dir; -} - - -/** Locate the application's library folder. - * - * The path is generated by the following pseudo-code evaluation: - * \code - * prefix + "/lib" - * \endcode - * - * @param default_lib_dir A default path which will used as fallback. - * @return A string containing the library folder's path, which must be freed when - * no longer necessary. If BinReloc is not initialized, or if the initialization - * function failed, then a copy of default_lib_dir will be returned. - * If default_lib_dir is NULL, then NULL will be returned. - */ -char * -br_find_lib_dir (const char *default_lib_dir) -{ - char *prefix, *dir; - - prefix = br_find_prefix ((const char *) NULL); - if (prefix == (char *) NULL) { - /* BinReloc not initialized. */ - if (default_lib_dir != (const char *) NULL) - return strdup (default_lib_dir); - else - return (char *) NULL; - } - - dir = br_build_path (prefix, "lib"); - free (prefix); - return dir; -} - - -/** Locate the application's libexec folder. - * - * The path is generated by the following pseudo-code evaluation: - * \code - * prefix + "/libexec" - * \endcode - * - * @param default_libexec_dir A default path which will used as fallback. - * @return A string containing the libexec folder's path, which must be freed when - * no longer necessary. If BinReloc is not initialized, or if the initialization - * function failed, then a copy of default_libexec_dir will be returned. - * If default_libexec_dir is NULL, then NULL will be returned. - */ -char * -br_find_libexec_dir (const char *default_libexec_dir) -{ - char *prefix, *dir; - - prefix = br_find_prefix ((const char *) NULL); - if (prefix == (char *) NULL) { - /* BinReloc not initialized. */ - if (default_libexec_dir != (const char *) NULL) - return strdup (default_libexec_dir); - else - return (char *) NULL; - } - - dir = br_build_path (prefix, "libexec"); - free (prefix); - return dir; -} - - -/** Locate the application's configuration files folder. - * - * The path is generated by the following pseudo-code evaluation: - * \code - * prefix + "/etc" - * \endcode - * - * @param default_etc_dir A default path which will used as fallback. - * @return A string containing the etc folder's path, which must be freed when - * no longer necessary. If BinReloc is not initialized, or if the initialization - * function failed, then a copy of default_etc_dir will be returned. - * If default_etc_dir is NULL, then NULL will be returned. - */ -char * -br_find_etc_dir (const char *default_etc_dir) -{ - char *prefix, *dir; - - prefix = br_find_prefix ((const char *) NULL); - if (prefix == (char *) NULL) { - /* BinReloc not initialized. */ - if (default_etc_dir != (const char *) NULL) - return strdup (default_etc_dir); - else - return (char *) NULL; - } - - dir = br_build_path (prefix, "etc"); - free (prefix); - return dir; -} - - -/*********************** - * Utility functions - ***********************/ - -/** Concatenate str1 and str2 to a newly allocated string. - * - * @param str1 A string. - * @param str2 Another string. - * @returns A newly-allocated string. This string should be freed when no longer needed. - */ -char * -br_strcat (const char *str1, const char *str2) -{ - char *result; - size_t len1, len2; - - if (str1 == NULL) - str1 = ""; - if (str2 == NULL) - str2 = ""; - - len1 = strlen (str1); - len2 = strlen (str2); - - result = (char *) malloc (len1 + len2 + 1); - memcpy (result, str1, len1); - memcpy (result + len1, str2, len2); - result[len1 + len2] = '\0'; - - return result; -} - - -char * -br_build_path (const char *dir, const char *file) -{ - char *dir2, *result; - size_t len; - int must_free = 0; - - len = strlen (dir); - if (len > 0 && dir[len - 1] != '/') { - dir2 = br_strcat (dir, "/"); - must_free = 1; - } else - dir2 = (char *) dir; - - result = br_strcat (dir2, file); - if (must_free) - free (dir2); - return result; -} - - -/* Emulates glibc's strndup() */ -static char * -br_strndup (const char *str, size_t size) -{ - char *result = (char *) NULL; - size_t len; - - if (str == (const char *) NULL) - return (char *) NULL; - - len = strlen (str); - if (len == 0) - return strdup (""); - if (size > len) - size = len; - - result = (char *) malloc (len + 1); - memcpy (result, str, size); - result[size] = '\0'; - return result; -} - - -/** Extracts the directory component of a path. - * - * Similar to g_dirname() or the dirname commandline application. - * - * Example: - * \code - * br_dirname ("/usr/local/foobar"); --> Returns: "/usr/local" - * \endcode - * - * @param path A path. - * @returns A directory name. This string should be freed when no longer needed. - */ -char * -br_dirname (const char *path) -{ - char *end, *result; - - if (path == (const char *) NULL) - return (char *) NULL; - - end = strrchr (path, '/'); - if (end == (const char *) NULL) - return strdup ("."); - - while (end > path && *end == '/') - end--; - result = br_strndup (path, end - path + 1); - if (result[0] == 0) { - free (result); - return strdup ("/"); - } else - return result; -} - - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#endif /* __BINRELOC_C__ */ diff --git a/sourcepawn/compiler/binreloc.h b/sourcepawn/compiler/binreloc.h deleted file mode 100644 index 4ee25c29..00000000 --- a/sourcepawn/compiler/binreloc.h +++ /dev/null @@ -1,80 +0,0 @@ -/* - * BinReloc - a library for creating relocatable executables - * Written by: Hongli Lai - * http://autopackage.org/ - * - * This source code is public domain. You can relicense this code - * under whatever license you want. - * - * See http://autopackage.org/docs/binreloc/ for - * more information and how to use this. - */ - -#ifndef __BINRELOC_H__ -#define __BINRELOC_H__ - -#ifdef __cplusplus -extern "C" { -#endif /* __cplusplus */ - - -/** These error codes can be returned by br_init(), br_init_lib(), gbr_init() or gbr_init_lib(). */ -typedef enum { - /** Cannot allocate memory. */ - BR_INIT_ERROR_NOMEM, - /** Unable to open /proc/self/maps; see errno for details. */ - BR_INIT_ERROR_OPEN_MAPS, - /** Unable to read from /proc/self/maps; see errno for details. */ - BR_INIT_ERROR_READ_MAPS, - /** The file format of /proc/self/maps is invalid; kernel bug? */ - BR_INIT_ERROR_INVALID_MAPS, - /** BinReloc is disabled (the ENABLE_BINRELOC macro is not defined). */ - BR_INIT_ERROR_DISABLED -} BrInitError; - - -#ifndef BINRELOC_RUNNING_DOXYGEN -/* Mangle symbol names to avoid symbol collisions with other ELF objects. */ - #define br_init SbCJ22537442193159_br_init - #define br_init_lib SbCJ22537442193159_br_init_lib - #define br_find_exe SbCJ22537442193159_br_find_exe - #define br_find_exe_dir SbCJ22537442193159_br_find_exe_dir - #define br_find_prefix SbCJ22537442193159_br_find_prefix - #define br_find_bin_dir SbCJ22537442193159_br_find_bin_dir - #define br_find_sbin_dir SbCJ22537442193159_br_find_sbin_dir - #define br_find_data_dir SbCJ22537442193159_br_find_data_dir - #define br_find_locale_dir SbCJ22537442193159_br_find_locale_dir - #define br_find_lib_dir SbCJ22537442193159_br_find_lib_dir - #define br_find_libexec_dir SbCJ22537442193159_br_find_libexec_dir - #define br_find_etc_dir SbCJ22537442193159_br_find_etc_dir - #define br_strcat SbCJ22537442193159_br_strcat - #define br_build_path SbCJ22537442193159_br_build_path - #define br_dirname SbCJ22537442193159_br_dirname - - -#endif -int br_init (BrInitError *error); -int br_init_lib (BrInitError *error); - -char *br_find_exe (const char *default_exe); -char *br_find_exe_dir (const char *default_dir); -char *br_find_prefix (const char *default_prefix); -char *br_find_bin_dir (const char *default_bin_dir); -char *br_find_sbin_dir (const char *default_sbin_dir); -char *br_find_data_dir (const char *default_data_dir); -char *br_find_locale_dir (const char *default_locale_dir); -char *br_find_lib_dir (const char *default_lib_dir); -char *br_find_libexec_dir (const char *default_libexec_dir); -char *br_find_etc_dir (const char *default_etc_dir); - -/* Utility functions */ -char *br_strcat (const char *str1, const char *str2); -char *br_build_path (const char *dir, const char *file); -char *br_dirname (const char *path); - - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#endif /* __BINRELOC_H__ */ diff --git a/sourcepawn/compiler/getch.h b/sourcepawn/compiler/getch.h deleted file mode 100644 index 71cdd83b..00000000 --- a/sourcepawn/compiler/getch.h +++ /dev/null @@ -1,15 +0,0 @@ -/* Extremely inefficient but portable POSIX getch(), see getch.c */ -#ifndef GETCH_H -#define GETCH_H - -#if defined __cplusplus - extern "C" { -#endif -int getch(void); -int kbhit(void); - -#if defined __cplusplus -} -#endif - -#endif /* GETCH_H */ diff --git a/sourcepawn/compiler/libpawnc.cpp b/sourcepawn/compiler/libpawnc.cpp deleted file mode 100644 index f7223fc8..00000000 --- a/sourcepawn/compiler/libpawnc.cpp +++ /dev/null @@ -1,346 +0,0 @@ -// vim: set sts=8 ts=2 sw=2 tw=99 noet: -/* LIBPAWNC.C - * - * A "glue file" for building the Pawn compiler as a DLL or shared library. - * - * Copyright (c) ITB CompuPhase, 2000-2006 - * - * This software is provided "as-is", without any express or implied warranty. - * In no event will the authors be held liable for any damages arising from - * the use of this software. - * - * Permission is granted to anyone to use this software for any purpose, - * including commercial applications, and to alter it and redistribute it - * freely, subject to the following restrictions: - * - * 1. The origin of this software must not be misrepresented; you must not - * claim that you wrote the original software. If you use this software in - * a product, an acknowledgment in the product documentation would be - * appreciated but is not required. - * 2. Altered source versions must be plainly marked as such, and must not be - * misrepresented as being the original software. - * 3. This notice may not be removed or altered from any source distribution. - * - * Version: $Id$ - */ -#include -#include -#include -#include -#include -#include "sc.h" -#include "memfile.h" - -#if defined LINUX || defined __FreeBSD__ || defined __OpenBSD__ || defined DARWIN -#include -#include -#endif - -/* pc_printf() - * Called for general purpose "console" output. This function prints general - * purpose messages; errors go through pc_error(). The function is modelled - * after printf(). - */ -int pc_printf(const char *message,...) -{ - int ret; - va_list argptr; - - va_start(argptr,message); - ret=vprintf(message,argptr); - va_end(argptr); - - return ret; -} - -/* pc_error() - * Called for producing error output. - * number the error number (as documented in the manual) - * message a string describing the error with embedded %d and %s tokens - * filename the name of the file currently being parsed - * firstline the line number at which the expression started on which - * the error was found, or -1 if there is no "starting line" - * lastline the line number at which the error was detected - * argptr a pointer to the first of a series of arguments (for macro - * "va_arg") - * Return: - * If the function returns 0, the parser attempts to continue compilation. - * On a non-zero return value, the parser aborts. - */ -int pc_error(int number,const char *message,const char *filename,int firstline,int lastline,va_list argptr) -{ -static const char *prefix[3]={ "error", "fatal error", "warning" }; - - if (number!=0) { - int idx; - - if (number < FIRST_FATAL_ERROR || (number >= 200 && sc_warnings_are_errors)) - idx = 0; - else if (number < 200) - idx = 1; - else - idx = 2; - - const char *pre=prefix[idx]; - if (firstline>=0) - fprintf(stdout,"%s(%d -- %d) : %s %03d: ",filename,firstline,lastline,pre,number); - else - fprintf(stdout,"%s(%d) : %s %03d: ",filename,lastline,pre,number); - } /* if */ - vfprintf(stdout,message,argptr); - fflush(stdout); - return 0; -} - -typedef struct src_file_s { - FILE *fp; // Set if writing. - char *buffer; // IO buffer. - char *pos; // IO position. - char *end; // End of buffer. - size_t maxlength; // Maximum length of the writable buffer. -} src_file_t; - -/* pc_opensrc() - * Opens a source file (or include file) for reading. The "file" does not have - * to be a physical file, one might compile from memory. - * filename the name of the "file" to read from - * Return: - * The function must return a pointer, which is used as a "magic cookie" to - * all I/O functions. When failing to open the file for reading, the - * function must return NULL. - * Note: - * Several "source files" may be open at the same time. Specifically, one - * file can be open for reading and another for writing. - */ -void *pc_opensrc(char *filename) -{ - FILE *fp = NULL; - long length; - src_file_t *src = NULL; - -#if defined LINUX || defined __FreeBSD__ || defined __OpenBSD__ || defined DARWIN - struct stat fileInfo; - if (stat(filename, &fileInfo) != 0) { - return NULL; - } - - if (S_ISDIR(fileInfo.st_mode)) { - return NULL; - } -#endif - - if ((fp = fopen(filename, "rb")) == NULL) - return NULL; - if (fseek(fp, 0, SEEK_END) == -1) - goto err; - if ((length = ftell(fp)) == -1) - goto err; - if (fseek(fp, 0, SEEK_SET) == -1) - goto err; - - if ((src = (src_file_t *)calloc(1, sizeof(src_file_t))) == NULL) - goto err; - if ((src->buffer = (char *)calloc(length, sizeof(char))) == NULL) - goto err; - if (fread(src->buffer, length, 1, fp) != 1) - goto err; - - src->pos = src->buffer; - src->end = src->buffer + length; - fclose(fp); - return src; - -err: - pc_closesrc(src); - fclose(fp); - return NULL; -} - -/* pc_createsrc() - * Creates/overwrites a source file for writing. The "file" does not have - * to be a physical file, one might compile from memory. - * filename the name of the "file" to create - * Return: - * The function must return a pointer which is used as a "magic cookie" to - * all I/O functions. When failing to open the file for reading, the - * function must return NULL. - * Note: - * Several "source files" may be open at the same time. Specifically, one - * file can be open for reading and another for writing. - */ -void *pc_createsrc(char *filename) -{ - src_file_t *src = (src_file_t *)calloc(1, sizeof(src_file_t)); - if (!src) - return NULL; - if ((src->fp = fopen(filename, "wt")) == NULL) { - pc_closesrc(src); - return NULL; - } - - src->maxlength = 1024; - if ((src->buffer = (char *)calloc(1, src->maxlength)) == NULL) { - pc_closesrc(src); - return NULL; - } - - src->pos = src->buffer; - src->end = src->buffer + src->maxlength; - return src; -} - -/* pc_closesrc() - * Closes a source file (or include file). The "handle" parameter has the - * value that pc_opensrc() returned in an earlier call. - */ -void pc_closesrc(void *handle) -{ - src_file_t *src = (src_file_t *)handle; - if (!src) - return; - if (src->fp) { - fwrite(src->buffer, src->pos - src->buffer, 1, src->fp); - fclose(src->fp); - } - free(src->buffer); - free(src); -} - -/* pc_readsrc() - * Reads a single line from the source file (or up to a maximum number of - * characters if the line in the input file is too long). - */ -char *pc_readsrc(void *handle,unsigned char *target,int maxchars) -{ - src_file_t *src = (src_file_t *)handle; - char *outptr = (char *)target; - char *outend = outptr + maxchars; - - assert(!src->fp); - - if (src->pos == src->end) - return NULL; - - while (outptr < outend && src->pos < src->end) { - char c = *src->pos++; - *outptr++ = c; - - if (c == '\n') - break; - if (c == '\r') { - // Handle CRLF. - if (src->pos < src->end && *src->pos == '\n') { - src->pos++; - if (outptr < outend) - *outptr++ = '\n'; - } else { - // Replace with \n. - *(outptr - 1) = '\n'; - } - break; - } - } - - // Caller passes in a buffer of size >= maxchars+1. - *outptr = '\0'; - return (char *)target; -} - -/* pc_writesrc() - * Writes to to the source file. There is no automatic line ending; to end a - * line, write a "\n". - */ -int pc_writesrc(void *handle,unsigned char *source) -{ - char *str = (char *)source; - size_t len = strlen(str); - src_file_t *src = (src_file_t *)handle; - - assert(src->fp && src->maxlength); - - if (src->pos + len > src->end) { - char *newbuf; - size_t newmax = src->maxlength; - size_t newlen = (src->pos - src->buffer) + len; - while (newmax < newlen) { - // Grow by 1.5X - newmax += newmax + newmax / 2; - if (newmax < src->maxlength) - abort(); - } - - newbuf = (char *)realloc(src->buffer, newmax); - if (!newbuf) - abort(); - src->pos = newbuf + (src->pos - src->buffer); - src->end = newbuf + newmax; - src->buffer = newbuf; - src->maxlength = newmax; - } - - strcpy(src->pos, str); - src->pos += len; - return 0; -} - -void *pc_getpossrc(void *handle,void *position) -{ - src_file_t *src = (src_file_t *)handle; - - assert(!src->fp); - return (void *)(ptrdiff_t)(src->pos - src->buffer); -} - -/* pc_resetsrc() - * "position" may only hold a pointer that was previously obtained from - * pc_getpossrc() - */ -void pc_resetsrc(void *handle,void *position) -{ - src_file_t *src = (src_file_t *)handle; - ptrdiff_t pos = (ptrdiff_t)position; - - assert(!src->fp); - assert(pos >= 0 && src->buffer + pos <= src->end); - src->pos = src->buffer + pos; -} - -int pc_eofsrc(void *handle) -{ - src_file_t *src = (src_file_t *)handle; - - assert(!src->fp); - return src->pos == src->end; -} - -/* should return a pointer, which is used as a "magic cookie" to all I/O - * functions; return NULL for failure - */ -void *pc_openasm(char *filename) -{ - return mfcreate(filename); -} - -void pc_closeasm(void *handle, int deletefile) -{ - if (handle!=NULL) { - if (!deletefile) - mfdump((MEMFILE*)handle); - mfclose((MEMFILE*)handle); - } /* if */ -} - -void pc_resetasm(void *handle) -{ - mfseek((MEMFILE*)handle,0,SEEK_SET); -} - -int pc_writeasm(void *handle,const char *string) -{ - return mfputs((MEMFILE*)handle,string); -} - -char *pc_readasm(void *handle, char *string, int maxchars) -{ - return mfgets((MEMFILE*)handle,string,maxchars); -} diff --git a/sourcepawn/compiler/lstring.cpp b/sourcepawn/compiler/lstring.cpp deleted file mode 100644 index 102a956e..00000000 --- a/sourcepawn/compiler/lstring.cpp +++ /dev/null @@ -1,124 +0,0 @@ -/* Safe string copying and concatenation - * These routines are originally distributed in two separate files. I have - * copied the files verbatim in this single source file, including all comments. - * The only change is that the second set of include files is commented out - * (there is no need to include the same files twice). - */ - -#include "lstring.h" - -#if !defined HAVE_SAFESTR - -/* $OpenBSD: strlcpy.c,v 1.10 2005/08/08 08:05:37 espie Exp $ */ - -/* - * Copyright (c) 1998 Todd C. Miller - * - * Permission to use, copy, modify, and distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - */ - -/* - #include already included through lstring.h - */ -#include /* for strlen() */ - -/* - * Copy src to string dst of size siz. At most siz-1 characters - * will be copied. Always NUL terminates (unless siz == 0). - * Returns strlen(src); if retval >= siz, truncation occurred. - */ -extern "C" size_t -strlcpy(char *dst, const char *src, size_t siz) -{ - char *d = dst; - const char *s = src; - size_t n = siz; - - /* Copy as many bytes as will fit */ - if (n != 0 && --n != 0) { - do { - if ((*d++ = *s++) == 0) - break; - } while (--n != 0); - } - - /* Not enough room in dst, add NUL and traverse rest of src */ - if (n == 0) { - if (siz != 0) - *d = '\0'; /* NUL-terminate dst */ - while (*s++) - ; - } - - return(s - src - 1); /* count does not include NUL */ -} - -/* $OpenBSD: strlcat.c,v 1.13 2005/08/08 08:05:37 espie Exp $ */ - -/* - * Copyright (c) 1998 Todd C. Miller - * - * Permission to use, copy, modify, and distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - */ - -/* - #include already included - #include already included -*/ - -/* - * Appends src to string dst of size siz (unlike strncat, siz is the - * full size of dst, not space left). At most siz-1 characters - * will be copied. Always NUL terminates (unless siz <= strlen(dst)). - * Returns strlen(src) + MIN(siz, strlen(initial dst)). - * If retval >= siz, truncation occurred. - */ -extern "C" size_t -strlcat(char *dst, const char *src, size_t siz) -{ - char *d = dst; - const char *s = src; - size_t n = siz; - size_t dlen; - - /* Find the end of dst and adjust bytes left but don't go past end */ - while (n-- != 0 && *d != '\0') - d++; - dlen = d - dst; - n = siz - dlen; - - if (n == 0) - return(dlen + strlen(s)); - while (*s != '\0') { - if (n != 1) { - *d++ = *s; - n--; - } - s++; - } - *d = '\0'; - - return(dlen + (s - src)); /* count does not include NUL */ -} - -#endif /* #if !defined HAVE_SAFESTR */ diff --git a/sourcepawn/compiler/lstring.h b/sourcepawn/compiler/lstring.h deleted file mode 100644 index f8206e11..00000000 --- a/sourcepawn/compiler/lstring.h +++ /dev/null @@ -1,26 +0,0 @@ -/* prototypes for strlcpy() and strlcat() */ - -#include - -#if defined __WATCOMC__ && __WATCOMC__ >= 1240 - /* OpenWatcom introduced BSD "safe string functions" with version 1.4 */ - #define HAVE_SAFESTR -#endif - -#if !defined HAVE_SAFESTR - -#if defined(__cplusplus) -# define EXPORT extern "C" -#else -# define EXPORT -#endif - -EXPORT size_t -strlcpy(char *dst, const char *src, size_t siz); - -EXPORT size_t -strlcat(char *dst, const char *src, size_t siz); - -#undef EXPORT - -#endif diff --git a/sourcepawn/compiler/memfile.cpp b/sourcepawn/compiler/memfile.cpp deleted file mode 100644 index bc572e7f..00000000 --- a/sourcepawn/compiler/memfile.cpp +++ /dev/null @@ -1,116 +0,0 @@ -#include "memfile.h" -#include -#include "osdefs.h" - -memfile_t *memfile_creat(const char *name, size_t init) -{ - memfile_t mf; - memfile_t *pmf; - - mf.size = init; - mf.base = (char *)malloc(init); - mf.usedoffs = 0; - if (!mf.base) - { - return NULL; - } - - mf.offs = 0; - mf._static = 0; - - pmf = (memfile_t *)malloc(sizeof(memfile_t)); - memcpy(pmf, &mf, sizeof(memfile_t)); - - pmf->name = strdup(name); - - return pmf; -} - -void memfile_destroy(memfile_t *mf) -{ - if (!mf) - { - return; - } - - if (!mf->_static) - { - free(mf->name); - free(mf->base); - free(mf); - } -} - -void memfile_seek(memfile_t *mf, long seek) -{ - mf->offs = seek; -} - -long memfile_tell(memfile_t *mf) -{ - return mf->offs; -} - -size_t memfile_read(memfile_t *mf, void *buffer, size_t maxsize) -{ - if (!maxsize || mf->offs >= mf->usedoffs) - { - return 0; - } - - if (mf->usedoffs - mf->offs < (long)maxsize) - { - maxsize = mf->usedoffs - mf->offs; - if (!maxsize) - { - return 0; - } - } - - memcpy(buffer, mf->base + mf->offs, maxsize); - - mf->offs += maxsize; - - return maxsize; -} - -int memfile_write(memfile_t *mf, const void *buffer, size_t size) -{ - if (mf->offs + size > mf->size) - { - size_t newsize = (mf->size + size) * 2; - if (mf->_static) - { - char *oldbase = mf->base; - mf->base = (char *)malloc(newsize); - if (!mf->base) - { - return 0; - } - memcpy(mf->base, oldbase, mf->size); - } else { - mf->base = (char *)realloc(mf->base, newsize); - if (!mf->base) - { - return 0; - } - } - mf->_static = 0; - mf->size = newsize; - } - memcpy(mf->base + mf->offs, buffer, size); - mf->offs += size; - - if (mf->offs > mf->usedoffs) - { - mf->usedoffs = mf->offs; - } - - return 1; -} - -void memfile_reset(memfile_t *mf) -{ - mf->usedoffs = 0; - mf->offs = 0; -} diff --git a/sourcepawn/compiler/memfile.h b/sourcepawn/compiler/memfile.h deleted file mode 100644 index 225e4d87..00000000 --- a/sourcepawn/compiler/memfile.h +++ /dev/null @@ -1,66 +0,0 @@ -#ifndef _INCLUDE_MEMFILE_H -#define _INCLUDE_MEMFILE_H - -#include - -typedef struct memfile_s -{ - char *name; - char *base; - long offs; - long usedoffs; - size_t size; - int _static; -} memfile_t; - -/** - * Creates a new memory file - * init is the initial size in bytes - */ -memfile_t *memfile_creat(const char *name, size_t init); - -/** - * Frees the memory associated. - */ -void memfile_destroy(memfile_t *mf); - -/** - * Seeks to a given offset (always from start) - */ -void memfile_seek(memfile_t *mf, long seek); - -/** - * Writes to a memory buffer (expands as necessary). - * Returns 1 on success, 0 on failure. - */ -int memfile_write(memfile_t *mf, const void *buffer, size_t size); - -/** - * Reads a number of bytes from a memory buffer. - * Returns the number of bytes read until the end was hit. - */ -size_t memfile_read(memfile_t *mf, void *buffer, size_t maxsize); - -/** - * Returns the current position from the start. - */ -long memfile_tell(memfile_t *mf); - -/** - * Resets all the states of the memory buffer. - * (does not actually free or zero memory) - */ -void memfile_reset(memfile_t *mf); - -typedef memfile_t MEMFILE; -MEMFILE *mfcreate(const char *filename); -void mfclose(MEMFILE *mf); -int mfdump(MEMFILE *mf); -long mflength(const MEMFILE *mf); -long mfseek(MEMFILE *mf,long offset,int whence); -unsigned int mfwrite(MEMFILE *mf,const unsigned char *buffer,unsigned int size); -unsigned int mfread(MEMFILE *mf,unsigned char *buffer,unsigned int size); -char *mfgets(MEMFILE *mf,char *string,unsigned int size); -int mfputs(MEMFILE *mf,const char *string); - -#endif //_INCLUDE_MEMFILE_H diff --git a/sourcepawn/compiler/memory-buffer.h b/sourcepawn/compiler/memory-buffer.h deleted file mode 100644 index 0a92c285..00000000 --- a/sourcepawn/compiler/memory-buffer.h +++ /dev/null @@ -1,103 +0,0 @@ -// vim: set sts=2 ts=8 sw=2 tw=99 et: -// -// Copyright (C) 2012-2014 AlliedModders LLC, David Anderson -// -// This file is part of SourcePawn. -// -// SourcePawn is free software: you can redistribute it and/or modify it under -// the terms of the GNU General Public License as published by the Free -// Software Foundation, either version 3 of the License, or (at your option) -// any later version. -// -// SourcePawn is distributed in the hope that it will be useful, but WITHOUT ANY -// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -// FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. -// -// You should have received a copy of the GNU General Public License along with -// SourcePawn. If not, see http://www.gnu.org/licenses/. -#ifndef _include_sp_memory_buffer_h_ -#define _include_sp_memory_buffer_h_ - -#include -#include -#include "smx-builder.h" - -// Interface for SmxBuilder to blit bytes. -class ISmxBuffer -{ - public: - virtual bool write(const void *bytes, size_t len) = 0; - virtual size_t pos() const = 0; -}; - -// An in-memory buffer for SmxBuilder. -class MemoryBuffer : public ISmxBuffer -{ - static const size_t kDefaultSize = 4096; - - public: - MemoryBuffer() { - buffer_ = (uint8_t *)calloc(kDefaultSize, 1); - pos_ = buffer_; - end_ = buffer_ + kDefaultSize; - } - ~MemoryBuffer() { - free(buffer_); - } - - bool write(const void *bytes, size_t len) KE_OVERRIDE { - if (pos_ + len > end_) - grow(len); - memcpy(pos_, bytes, len); - pos_ += len; - return true; - } - - size_t pos() const KE_OVERRIDE { - return pos_ - buffer_; - } - - uint8_t *bytes() const { - return buffer_; - } - size_t size() const { - return pos(); - } - void rewind(size_t newpos) { - assert(newpos < pos()); - pos_ = buffer_ + newpos; - } - - private: - void grow(size_t len) { - if (!ke::IsUintPtrAddSafe(pos(), len)) { - fprintf(stderr, "Allocation overflow!\n"); - abort(); - } - - size_t new_maxsize = end_ - buffer_; - while (pos() + len > new_maxsize) { - if (!ke::IsUintPtrMultiplySafe(new_maxsize, 2)) { - fprintf(stderr, "Allocation overflow!\n"); - abort(); - } - new_maxsize *= 2; - } - - uint8_t *newbuffer = (uint8_t *)realloc(buffer_, new_maxsize); - if (!newbuffer) { - fprintf(stderr, "Out of memory!\n"); - abort(); - } - pos_ = newbuffer + (pos_ - buffer_); - end_ = newbuffer + new_maxsize; - buffer_ = newbuffer; - } - - private: - uint8_t *buffer_; - uint8_t *pos_; - uint8_t *end_; -}; - -#endif // _include_sp_memory_buffer_h_ diff --git a/sourcepawn/compiler/osdefs.h b/sourcepawn/compiler/osdefs.h deleted file mode 100644 index 49ec2dca..00000000 --- a/sourcepawn/compiler/osdefs.h +++ /dev/null @@ -1,111 +0,0 @@ -/* __MSDOS__ set when compiling for DOS (not Windows) - * _Windows set when compiling for any version of Microsoft Windows - * __WIN32__ set when compiling for Windows95 or WindowsNT (32 bit mode) - * __32BIT__ set when compiling in 32-bit "flat" mode (DOS or Windows) - * - * Copyright 1998-2005, ITB CompuPhase, The Netherlands. - * info@compuphase.com. - */ - -#ifndef _OSDEFS_H -#define _OSDEFS_H - -/* Every compiler uses different "default" macros to indicate the mode - * it is in. Throughout the source, we use the Borland C++ macros, so - * the macros of Watcom C/C++ and Microsoft Visual C/C++ are mapped to - * those of Borland C++. - */ -#if defined(__WATCOMC__) -# if defined(__WINDOWS__) || defined(__NT__) -# define _Windows 1 -# endif -# ifdef __386__ -# define __32BIT__ 1 -# endif -# if defined(_Windows) && defined(__32BIT__) -# define __WIN32__ 1 -# endif -#elif defined(_MSC_VER) -# if defined(_WINDOWS) || defined(_WIN32) -# define _Windows 1 -# endif -# ifdef _WIN32 -# define __WIN32__ 1 -# define __32BIT__ 1 -# endif -# if _MSC_VER >= 1400 -# if !defined _CRT_SECURE_NO_DEPRECATE -# define _CRT_SECURE_NO_DEPRECATE -# endif -# define strdup _strdup -# define stricmp _stricmp -# define access _access -# define chdir _chdir -# define strdup _strdup -# define unlink _unlink -# endif -#endif - -#if defined __FreeBSD__ - #include -#elif defined __APPLE__ - #include -#elif defined LINUX - #include -#endif - -/* Linux NOW has these */ -#if !defined BIG_ENDIAN - #define BIG_ENDIAN 4321 -#endif -#if !defined LITTLE_ENDIAN - #define LITTLE_ENDIAN 1234 -#endif - -/* educated guess, BYTE_ORDER is undefined, i386 is common => little endian */ -#if !defined BYTE_ORDER - #if defined UCLINUX - #define BYTE_ORDER BIG_ENDIAN - #else - #define BYTE_ORDER LITTLE_ENDIAN - #endif -#endif - -#if defined __MSDOS__ || defined __WIN32__ || defined _Windows - #define DIRSEP_CHAR '\\' -#elif defined macintosh - #define DIRSEP_CHAR ':' -#else - #define DIRSEP_CHAR '/' /* directory separator character */ -#endif - -/* _MAX_PATH is sometimes called differently and it may be in limits.h or - * stdlib.h instead of stdio.h. - */ -#if !defined _MAX_PATH - /* not defined, perhaps stdio.h was not included */ - #if !defined PATH_MAX - #include - #endif - #if !defined _MAX_PATH && !defined PATH_MAX - /* no _MAX_PATH and no MAX_PATH, perhaps it is in limits.h */ - #include - #endif - #if !defined _MAX_PATH && !defined PATH_MAX - /* no _MAX_PATH and no MAX_PATH, perhaps it is in stdlib.h */ - #include - #endif - /* if _MAX_PATH is undefined, try common alternative names */ - #if !defined _MAX_PATH - #if defined MAX_PATH - #define _MAX_PATH MAX_PATH - #elif defined _POSIX_PATH_MAX - #define _MAX_PATH _POSIX_PATH_MAX - #else - /* everything failed, actually we have a problem here... */ - #define _MAX_PATH 1024 - #endif - #endif -#endif - -#endif /* _OSDEFS_H */ diff --git a/sourcepawn/compiler/pawn.ico b/sourcepawn/compiler/pawn.ico deleted file mode 100644 index 7a6ab60bc5be72862ee6fee5e3bd4585a6644f36..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 8478 zcmeI1J!~6C7RN`X0-1jOasId_?ko&&fT6+xS*394Ykk$=3c7X~x^Y9`0H!do zU5Z1HN;p`{=BPq$&)d5&1?24JqK^}mD=Z*^=YId$U22!&QoJ_M$p4+M_ujmDGn|?C zY|N7R#N4}QLi%CNm_Jc!G}8KCJ~8GaZH=tq%Ozvn7slMWmG=K|)tJAotDZ9a`-(At z{Jk+>(k+pH21^DarFxo8f4gen)6ELqtg^eiYj#Jw=KFt+&GPcHxq9`gSzTQ<&1TbF zzkc1^xN*bWxpT+dy?fU@di2OVeE86`S}k+`{(bZ8*)#J@a`{jUh0sF9Qga{z2~dLt z4n!aU9*D>S2O^LF55#DJ0})7o2NGt10})7oSKU(w34kK}Ild7{fCo~*0tX_H01u>; z1r9_Y0Uk(E3mk|*0z8oN7B~=r1bASXkOL7&fCmU?WEcJ-z6tO^leWNt2qeG*8Nvbw zB9H(X#sUW-kN^*4EDIu#01sq53nGvJ&xi?M88O13`b%V7S%x~4j2%Hi8^*T4iHDslm->rW7>Dp%>D(KSYTU|S<<~Y9H>4gMKU}!g6jn!&~>nXLqDM!1_ar9Z`03QPV7AbH@CFu7n=~qPG zkK?%Cha>0&{b?orIHiUm4h%tjYmSLh`eA(tLnozfwJXIN6HA%VXaI4mi7HCm4b@4i z^jsj#=-buiL`>XIiCay`1IIjdj5&e4t)(JiOE~7tR%&*7@vu%BjpBH#=i2kdn?AEm z(_2lY-|KLy%}McFC6Tgbe0rVM9BSs9r#|b;9GJ{pdQ*?Xh6tKy#!u#x(>n-5Nb~jr z)G$czAfKCcku(T9wC5I4Cdlg{f2+gRSwuQC+I1av#093ANZaZ4CB60Sq~(HwbZ^bw z_+$}bZ{9lzudfb*Gj@RaD}) z=)>_3eFeo-bDdM2Y4qZ$_UdYVI2cs;KHmR$jdzguAN3?6u|f}&kBzyxNS@Q@`L7v2 z`8VRv^IU#jpU(4s->r$w``wjtp6QwEJITj4Q@Ta-TyE7kdAnIk*F{Bwv22Jl9)b;-@ZAnUT6`<8$e!;x%6SscZ)Mi1Hip8p-9gUHYl`lD||+PI-Gz2fnEdQ#u9TLbBOHPM`jHeB)h0XL0$+j2eY8wvM(V1Kk8GoY{#3b)o3awbNH622m-o?cKW=)ma&+)y zfB)d{c&uY!Ivsw!zV6(5yVYp44}PBRHK%EaQ^7ZE`8` zmYZptyuXj9Ubx2d=1Kkm>&-BIslQTtsQQE&=E(1FDIRowZ{+gB(pSgR#@ZPy{;buL zh$o@Da)!qWp9GTGQ#cB-cu~xbSFyvjzmYL}iUaN75HFq0KaPnX5N;?x#qzn64@dtZ ze!(b(wo;Mk^C;fxm)c5|z52QML2%EzxX5yMi;(*~4Y}NMd*z}Fa($;eUDWkZ0-2AM8fMoHg+Orq*V!GLeM( zMk9Og&8iQ#Z8LqniN3aJH}u+?B&!EvZBng$jzmVxQ*CoN+}_q}FHNdLkyjaT6Zw_BT&6^Jd!x`T4bQX{MQx*?jp~gvZ9@Owr|Jc5XZ16`(s)ewY&tN|S*%NVaRAGI zxSyE|b+ -#include -#include -#include -#include "memfile.h" -#include "osdefs.h" -#if defined LINUX || defined DARWIN -#include -#elif defined WIN32 -#include -#endif -#include "sc.h" - -int main(int argc, char *argv[]) -{ - return pc_compile(argc,argv); -} - -#if defined __linux__ || defined __APPLE__ -extern "C" void __cxa_pure_virtual(void) -{ -} - -void *operator new(size_t size) -{ - return malloc(size); -} - -void *operator new[](size_t size) -{ - return malloc(size); -} - -void operator delete(void *ptr) -{ - free(ptr); -} - -void operator delete[](void * ptr) -{ - free(ptr); -} -#endif diff --git a/sourcepawn/compiler/sc.h b/sourcepawn/compiler/sc.h deleted file mode 100644 index a930749e..00000000 --- a/sourcepawn/compiler/sc.h +++ /dev/null @@ -1,1014 +0,0 @@ -// vim: set sts=2 ts=8 sw=2 tw=99 et: -/* Pawn compiler - * - * Drafted after the Small-C compiler Version 2.01, originally created - * by Ron Cain, july 1980, and enhanced by James E. Hendrix. - * - * This version comes close to a complete rewrite. - * - * Copyright R. Cain, 1980 - * Copyright J.E. Hendrix, 1982, 1983 - * Copyright ITB CompuPhase, 1997-2006 - * - * This software is provided "as-is", without any express or implied warranty. - * In no event will the authors be held liable for any damages arising from - * the use of this software. - * - * Permission is granted to anyone to use this software for any purpose, - * including commercial applications, and to alter it and redistribute it - * freely, subject to the following restrictions: - * - * 1. The origin of this software must not be misrepresented; you must not - * claim that you wrote the original software. If you use this software in - * a product, an acknowledgment in the product documentation would be - * appreciated but is not required. - * 2. Altered source versions must be plainly marked as such, and must not be - * misrepresented as being the original software. - * 3. This notice may not be removed or altered from any source distribution. - * - * Version: $Id$ - */ -#ifndef SC_H_INCLUDED -#define SC_H_INCLUDED -#include -#include -#include -#if defined __BORLANDC__ && defined _Windows && !(defined __32BIT__ || defined __WIN32__) - /* setjmp() and longjmp() not well supported in 16-bit windows */ - #include - typedef int jmp_buf[9]; - #define setjmp(b) Catch(b) - #define longjmp(b,e) Throw(b,e) -#else - #include -#endif -#include "osdefs.h" -#include "amx.h" - -/* Note: the "cell" and "ucell" types are defined in AMX.H */ - -#define PUBLIC_CHAR '@' /* character that defines a function "public" */ -#define CTRL_CHAR '\\' /* default control character */ -#define sCHARBITS 8 /* size of a packed character */ - -#define MAXTAGS 16 -#define sDIMEN_MAX 4 /* maximum number of array dimensions */ -#define sLINEMAX 4095 /* input line length (in characters) */ -#define sCOMP_STACK 32 /* maximum nesting of #if .. #endif sections */ -#define sDEF_LITMAX 500 /* initial size of the literal pool, in "cells" */ -#define sDEF_AMXSTACK 4096 /* default stack size for AMX files */ -#define PREPROC_TERM '\x7f'/* termination character for preprocessor expressions (the "DEL" code) */ -#define sDEF_PREFIX "sourcemod.inc" /* default prefix filename */ -#define sARGS_MAX 32 /* number of arguments a function can have, max */ -#define sTAGS_MAX 16 /* maximum number of tags on an argument */ - -typedef union { - void *pv; /* e.g. a name */ - int i; -} stkitem; /* type of items stored on the compiler stack */ - -typedef struct s_arginfo { /* function argument info */ - char name[sNAMEMAX+1]; - char ident; /* iVARIABLE, iREFERENCE, iREFARRAY or iVARARGS */ - char usage; /* uCONST */ - int *tags; /* argument tag id. list */ - int numtags; /* number of tags in the tag list */ - int dim[sDIMEN_MAX]; - int idxtag[sDIMEN_MAX]; - int numdim; /* number of dimensions */ - unsigned char hasdefault; /* bit0: is there a default value? bit6: "tagof"; bit7: "sizeof" */ - union { - cell val; /* default value */ - struct { - cell *data; /* values of default array */ - int size; /* complete length of default array */ - int arraysize; /* size to reserve on the heap */ - cell addr; /* address of the default array in the data segment */ - } array; - } defvalue; /* default value, or pointer to default array */ - int defvalue_tag; /* tag of the default value */ -} arginfo; - -/* Equate table, tagname table, library table */ -typedef struct s_constvalue { - struct s_constvalue *next; - char name[sNAMEMAX+1]; - cell value; - int index; /* index level, for constants referring to array sizes/tags - * automaton id. for states and automatons - * tag for enumeration lists */ -} constvalue; - -struct methodmap_t; - -/* Symbol table format - * - * The symbol name read from the input file is stored in "name", the - * value of "addr" is written to the output file. The address in "addr" - * depends on the class of the symbol: - * global offset into the data segment - * local offset relative to the stack frame - * label generated hexadecimal number - * function offset into code segment - */ -typedef struct s_symbol { - struct s_symbol *next; - struct s_symbol *parent; /* hierarchical types */ - char name[sNAMEMAX+1]; - uint32_t hash; /* value derived from name, for quicker searching */ - cell addr; /* address or offset (or value for constant, index for native function) */ - cell codeaddr; /* address (in the code segment) where the symbol declaration starts */ - char vclass; /* sLOCAL if "addr" refers to a local symbol */ - char ident; /* see below for possible values */ - short usage; /* see below for possible values */ - char flags; /* see below for possible values */ - int compound; /* compound level (braces nesting level) */ - int tag; /* tagname id */ - union { - int declared; /* label: how many local variables are declared */ - struct { - int index; /* array & enum: tag of array indices or the enum item */ - int field; /* enumeration fields, where a size is attached to the field */ - } tags; /* extra tags */ - constvalue *lib; /* native function: library it is part of */ - long stacksize; /* normal/public function: stack requirements */ - } x; /* 'x' for 'extra' */ - union { - arginfo *arglist; /* types of all parameters for functions */ - constvalue *enumlist;/* list of names for the "root" of an enumeration */ - struct { - cell length; /* arrays: length (size) */ - cell slength; /* if a string index, this will be set to the original size */ - short level; /* number of dimensions below this level */ - } array; - } dim; /* for 'dimension', both functions and arrays */ - constvalue *states; /* list of state function/state variable ids + addresses */ - int fnumber; /* static global variables: file number in which the declaration is visible */ - int lnumber; /* line number (in the current source file) for the declaration */ - struct s_symbol **refer; /* referrer list, functions that "use" this symbol */ - int numrefers; /* number of entries in the referrer list */ - char *documentation; /* optional documentation string */ - methodmap_t *methodmap; /* if ident == iMETHODMAP */ - int funcid; /* set for functions during codegen */ -} symbol; - -/* Possible entries for "ident". These are used in the "symbol", "value" - * and arginfo structures. Not every constant is valid for every use. - * In an argument list, the list is terminated with a "zero" ident; labels - * cannot be passed as function arguments, so the value 0 is overloaded. - */ -#define iLABEL 0 -#define iVARIABLE 1 /* cell that has an address and that can be fetched directly (lvalue) */ -#define iREFERENCE 2 /* iVARIABLE, but must be dereferenced */ -#define iARRAY 3 -#define iREFARRAY 4 /* an array passed by reference (i.e. a pointer) */ -#define iARRAYCELL 5 /* array element, cell that must be fetched indirectly */ -#define iARRAYCHAR 6 /* array element, character from cell from array */ -#define iEXPRESSION 7 /* expression result, has no address (rvalue) */ -#define iCONSTEXPR 8 /* constant expression (or constant symbol) */ -#define iFUNCTN 9 -#define iREFFUNC 10 -#define iVARARGS 11 /* function specified ... as argument(s) */ -#define iACCESSOR 13 /* property accessor via a methodmap_method_t */ -#define iMETHODMAP 14 /* symbol defining a methodmap */ - -/* Possible entries for "usage" - * - * This byte is used as a serie of bits, the syntax is different for - * functions and other symbols: - * - * VARIABLE - * bits: 0 (uDEFINE) the variable is defined in the source file - * 1 (uREAD) the variable is "read" (accessed) in the source file - * 2 (uWRITTEN) the variable is altered (assigned a value) - * 3 (uCONST) the variable is constant (may not be assigned to) - * 4 (uPUBLIC) the variable is public - * 6 (uSTOCK) the variable is discardable (without warning) - * - * FUNCTION - * bits: 0 (uDEFINE) the function is defined ("implemented") in the source file - * 1 (uREAD) the function is invoked in the source file - * 2 (uRETVALUE) the function returns a value (or should return a value) - * 3 (uPROTOTYPED) the function was prototyped (implicitly via a definition or explicitly) - * 4 (uPUBLIC) the function is public - * 5 (uNATIVE) the function is native - * 6 (uSTOCK) the function is discardable (without warning) - * 7 (uMISSING) the function is not implemented in this source file - * 8 (uFORWARD) the function is explicitly forwardly declared - * - * CONSTANT - * bits: 0 (uDEFINE) the symbol is defined in the source file - * 1 (uREAD) the constant is "read" (accessed) in the source file - * 2 (uWRITTEN) redundant, but may be set for constants passed by reference - * 3 (uPREDEF) the constant is pre-defined and should be kept between passes - * 5 (uENUMROOT) the constant is the "root" of an enumeration - * 6 (uENUMFIELD) the constant is a field in a named enumeration - */ -#define uDEFINE 0x001 -#define uREAD 0x002 -#define uWRITTEN 0x004 -#define uRETVALUE 0x004 /* function returns (or should return) a value */ -#define uCONST 0x008 -#define uPROTOTYPED 0x008 -#define uPREDEF 0x008 /* constant is pre-defined */ -#define uPUBLIC 0x010 -#define uNATIVE 0x020 -#define uENUMROOT 0x020 -#define uSTOCK 0x040 -#define uENUMFIELD 0x040 -#define uMISSING 0x080 -#define uFORWARD 0x100 -#define uSTRUCT 0x200 /* :TODO: make this an ident */ -/* uRETNONE is not stored in the "usage" field of a symbol. It is - * used during parsing a function, to detect a mix of "return;" and - * "return value;" in a few special cases. - */ -#define uRETNONE 0x10 - -#define flgDEPRECATED 0x01 /* symbol is deprecated (avoid use) */ - -#define uMAINFUNC "main" -#define uENTRYFUNC "entry" - -#define sGLOBAL 0 /* global variable/constant class (no states) */ -#define sLOCAL 1 /* local variable/constant */ -#define sSTATIC 2 /* global life, local scope */ - -#define sSTATEVAR 3 /* criterion to find variables (sSTATEVAR implies a global variable) */ - -struct methodmap_method_s; - -typedef struct value_s { - symbol *sym; /* symbol in symbol table, NULL for (constant) expression */ - cell constval; /* value of the constant expression (if ident==iCONSTEXPR) - * also used for the size of a literal array */ - int tag; /* tag (of the expression) */ - int cmptag; /* for searching symbols: choose the one with the matching tag */ - char ident; /* iCONSTEXPR, iVARIABLE, iARRAY, iARRAYCELL, - * iEXPRESSION or iREFERENCE */ - char boolresult; /* boolean result for relational operators */ - cell *arrayidx; /* last used array indices, for checking self assignment */ - - /* when ident == iACCESSOR */ - struct methodmap_method_s *accessor; -} value; - -/* Wrapper around value + l/rvalue bit. */ -typedef struct svalue_s { - value val; - int lvalue; -} svalue; - -#define DECLFLAG_ARGUMENT 0x02 // The declaration is for an argument. -#define DECLFLAG_VARIABLE 0x04 // The declaration is for a variable. -#define DECLFLAG_ENUMROOT 0x08 // Multi-dimensional arrays should have an enumroot. -#define DECLFLAG_MAYBE_FUNCTION 0x10 // Might be a named function. -#define DECLFLAG_DYNAMIC_ARRAYS 0x20 // Dynamic arrays are allowed. -#define DECLFLAG_OLD 0x40 // Known old-style declaration. -#define DECLFLAG_FIELD 0x80 // Struct field. -#define DECLFLAG_NEW 0x100 // Known new-style declaration. -#define DECLMASK_NAMED_DECL (DECLFLAG_ARGUMENT | DECLFLAG_VARIABLE | DECLFLAG_MAYBE_FUNCTION | DECLFLAG_FIELD) - -typedef struct { - // Array information. - int numdim; - int dim[sDIMEN_MAX]; - int idxtag[sDIMEN_MAX]; - cell size; - constvalue *enumroot; - - // Type information. - int tag; // Same as tags[0]. - int tags[MAXTAGS]; // List of tags if multi-tagged. - int numtags; // Number of tags found. - int ident; // Either iREFERENCE, iARRAY, or iVARIABLE. - char usage; // Usage flags. - bool is_new; // New-style declaration. - bool has_postdims; // Dimensions, if present, were in postfix position. - - bool isCharArray() const; -} typeinfo_t; - -/* For parsing declarations. */ -typedef struct { - char name[sNAMEMAX + 1]; - typeinfo_t type; - int opertok; // Operator token, if applicable. -} declinfo_t; - -/* "while" statement queue (also used for "for" and "do - while" loops) */ -enum { - wqBRK, /* used to restore stack for "break" */ - wqCONT, /* used to restore stack for "continue" */ - wqLOOP, /* loop start label number */ - wqEXIT, /* loop exit label number (jump if false) */ - /* --- */ - wqSIZE /* "while queue" size */ -}; -#define wqTABSZ (24*wqSIZE) /* 24 nested loop statements */ - -enum { - statIDLE, /* not compiling yet */ - statFIRST, /* first pass */ - statWRITE, /* writing output */ - statSKIP, /* skipping output */ -}; - -typedef struct s_stringlist { - struct s_stringlist *next; - union { - char *line; - struct s_stringlist *tail; - }; -} stringlist; - -typedef struct s_stringpair { - struct s_stringpair *next; - char *first; - char *second; - int matchlength; - char flags; - char *documentation; -} stringpair; - -// Helper for token info. -typedef struct { - int id; - cell val; - char *str; -} token_t; - -// The method name buffer is larger since we can include our parent class's -// name, a "." to separate it, a "~" for constructors, or a ".get/.set" for -// accessors. -#define METHOD_NAMEMAX sNAMEMAX * 2 + 6 - -typedef struct { - token_t tok; - char name[METHOD_NAMEMAX + 1]; -} token_ident_t; - -/* macros for code generation */ -#define opcodes(n) ((n)*sizeof(cell)) /* opcode size */ -#define opargs(n) ((n)*sizeof(cell)) /* size of typical argument */ - -/* Tokens recognized by lex() - * Some of these constants are assigned as well to the variable "lastst" (see SC1.C) - */ -enum TokenKind { - /* value of first multi-character operator */ - tFIRST = 256, - /* multi-character operators */ - taMULT = tFIRST, /* *= */ - taDIV, /* /= */ - taMOD, /* %= */ - taADD, /* += */ - taSUB, /* -= */ - taSHL, /* <<= */ - taSHRU, /* >>>= */ - taSHR, /* >>= */ - taAND, /* &= */ - taXOR, /* ^= */ - taOR, /* |= */ - tlOR, /* || */ - tlAND, /* && */ - tlEQ, /* == */ - tlNE, /* != */ - tlLE, /* <= */ - tlGE, /* >= */ - tSHL, /* << */ - tSHRU, /* >>> */ - tSHR, /* >> */ - tINC, /* ++ */ - tDEC, /* -- */ - tELLIPS, /* ... */ - tDBLDOT, /* .. */ - tDBLCOLON, /* :: */ - /* value of last multi-character operator */ - tMIDDLE = tDBLCOLON, -/* reserved words (statements) */ - tACQUIRE, - tAS, - tASSERT, - tBEGIN, - tBREAK, - tBUILTIN, - tCATCH, - tCASE, - tCAST_TO, - tCELLSOF, - tCHAR, - tCONST, - tCONTINUE, - tDECL, - tDEFAULT, - tDEFINED, - tDELETE, - tDO, - tDOUBLE, - tELSE, - tEND, - tENUM, - tEXIT, - tEXPLICIT, - tFINALLY, - tFOR, - tFOREACH, - tFORWARD, - tFUNCENUM, - tFUNCTAG, - tFUNCTION, - tGOTO, - tIF, - tIMPLICIT, - tIMPORT, - tIN, - tINT, - tINT8, - tINT16, - tINT32, - tINT64, - tINTERFACE, - tINTN, - tLET, - tMETHODMAP, - tNAMESPACE, - tNATIVE, - tNEW, - tNULL, - tNULLABLE, - tOBJECT, - tOPERATOR, - tPACKAGE, - tPRIVATE, - tPROTECTED, - tPUBLIC, - tREADONLY, - tRETURN, - tSEALED, - tSIZEOF, - tSLEEP, - tSTATIC, - tSTOCK, - tSTRUCT, - tSWITCH, - tTAGOF, - tTHEN, - tTHIS, - tTHROW, - tTRY, - tTYPEDEF, - tTYPEOF, - tTYPESET, - tUINT8, - tUINT16, - tUINT32, - tUINT64, - tUINTN, - tUNION, - tUSING, - tVAR, - tVARIANT, - tVIEW_AS, - tVIRTUAL, - tVOID, - tVOLATILE, - tWHILE, - tWITH, - /* compiler directives */ - tpASSERT, /* #assert */ - tpDEFINE, - tpELSE, /* #else */ - tpELSEIF, /* #elseif */ - tpENDIF, - tpENDINPUT, - tpENDSCRPT, - tpERROR, - tpFILE, - tpIF, /* #if */ - tINCLUDE, - tpLINE, - tpPRAGMA, - tpTRYINCLUDE, - tpUNDEF, - tLAST = tpUNDEF, /* value of last multi-character match-able token */ - /* semicolon is a special case, because it can be optional */ - tTERM, /* semicolon or newline */ - tENDEXPR, /* forced end of expression */ - /* other recognized tokens */ - tNUMBER, /* integer number */ - tRATIONAL, /* rational number */ - tSYMBOL, - tLABEL, - tSTRING, - tPENDING_STRING, /* string, but not yet dequeued */ - tEXPR, /* for assigment to "lastst" only (see SC1.C) */ - tENDLESS, /* endless loop, for assigment to "lastst" only */ - tEMPTYBLOCK, /* empty blocks for AM bug 4825 */ - tEOL, /* newline, only returned by peek_new_line() */ - tNEWDECL, /* for declloc() */ - tLAST_TOKEN_ID -}; - -/* (reversed) evaluation of staging buffer */ -#define sSTARTREORDER 0x01 -#define sENDREORDER 0x02 -#define sEXPRSTART 0x80 /* top bit set, rest is free */ -#define sMAXARGS 127 /* relates to the bit pattern of sEXPRSTART */ - -#define sDOCSEP 0x01 /* to separate documentation comments between functions */ - -/* codes for ffabort() */ -#define xEXIT 1 /* exit code in PRI */ -#define xASSERTION 2 /* abort caused by failing assertion */ -#define xSTACKERROR 3 /* stack/heap overflow */ -#define xBOUNDSERROR 4 /* array index out of bounds */ -#define xMEMACCESS 5 /* data access error */ -#define xINVINSTR 6 /* invalid instruction */ -#define xSTACKUNDERFLOW 7 /* stack underflow */ -#define xHEAPUNDERFLOW 8 /* heap underflow */ -#define xCALLBACKERR 9 /* no, or invalid, callback */ -#define xSLEEP 12 /* sleep, exit code in PRI, tag in ALT */ - -/* Miscellaneous */ -#if !defined TRUE - #define FALSE 0 - #define TRUE 1 -#endif -#define sIN_CSEG 1 /* if parsing CODE */ -#define sIN_DSEG 2 /* if parsing DATA */ -#define sCHKBOUNDS 1 /* bit position in "debug" variable: check bounds */ -#define sSYMBOLIC 2 /* bit position in "debug" variable: symbolic info */ -#define sRESET 0 /* reset error flag */ -#define sFORCESET 1 /* force error flag on */ -#define sEXPRMARK 2 /* mark start of expression */ -#define sEXPRRELEASE 3 /* mark end of expression */ -#define sSETPOS 4 /* set line number for the error */ - -enum { - sOPTIMIZE_NONE, /* no optimization */ - sOPTIMIZE_NOMACRO, /* no macro instructions */ - sOPTIMIZE_DEFAULT, /* full optimization */ - /* ----- */ - sOPTIMIZE_NUMBER -}; - -typedef enum s_regid { - sPRI, /* indicates the primary register */ - sALT, /* indicates the secundary register */ -} regid; - -typedef enum s_optmark { - sEXPR, /* end of expression (for expressions that form a statement) */ - sPARM, /* end of parameter (in a function parameter list) */ - sLDECL, /* start of local declaration (variable) */ -} optmark; - -#define suSLEEP_INSTR 0x01 /* the "sleep" instruction was used */ - -#define FIXEDTAG 0x40000000 -#define FUNCTAG 0x20000000 -#define OBJECTTAG 0x10000000 -#define ENUMTAG 0x08000000 -#define METHODMAPTAG 0x04000000 -#define STRUCTTAG 0x02000000 -#define TAGTYPEMASK (FUNCTAG | OBJECTTAG | ENUMTAG | METHODMAPTAG | STRUCTTAG) -#define TAGFLAGMASK (FIXEDTAG | TAGTYPEMASK) -#define TAGID(tag) ((tag) & ~(TAGFLAGMASK)) -#define CELL_MAX (((ucell)1 << (sizeof(cell)*8-1)) - 1) - - -/* - * Functions you call from the "driver" program - */ -int pc_compile(int argc, char **argv); -int pc_addconstant(const char *name,cell value,int tag); -int pc_addtag(const char *name); -int pc_addtag_flags(const char *name, int flags); -int pc_findtag(const char *name); -constvalue *pc_tagptr(const char *name); -int pc_enablewarning(int number,int enable); -const char *pc_tagname(int tag); -int parse_decl(declinfo_t *decl, int flags); -const char *type_to_name(int tag); -bool parse_new_typename(const token_t *tok, int *tagp); - -/* - * Functions called from the compiler (to be implemented by you) - */ - -/* general console output */ -int pc_printf(const char *message,...); - -/* error report function */ -int pc_error(int number,const char *message,const char *filename,int firstline,int lastline,va_list argptr); - -/* input from source file */ -void *pc_opensrc(char *filename); /* reading only */ -void *pc_createsrc(char *filename); -void pc_closesrc(void *handle); /* never delete */ -char *pc_readsrc(void *handle,unsigned char *target,int maxchars); -int pc_writesrc(void *handle,unsigned char *source); -void *pc_getpossrc(void *handle,void *position); /* mark the current position */ -void pc_resetsrc(void *handle,void *position); /* reset to a position marked earlier */ -int pc_eofsrc(void *handle); - -/* output to intermediate (.ASM) file */ -void *pc_openasm(char *filename); /* read/write */ -void pc_closeasm(void *handle,int deletefile); -void pc_resetasm(void *handle); -int pc_writeasm(void *handle,const char *str); -char *pc_readasm(void *handle,char *target,int maxchars); - -void sp_fdbg_ntv_start(int num_natives); -void sp_fdbg_ntv_hook(int index, symbol *sym); - -/* function prototypes in SC1.C */ -void set_extension(char *filename,const char *extension,int force); -symbol *fetchfunc(char *name); -char *operator_symname(char *symname,const char *opername,int tag1,int tag2,int numtags,int resulttag); -char *funcdisplayname(char *dest,char *funcname); -int exprconst(cell *val,int *tag,symbol **symptr); -constvalue *append_constval(constvalue *table,const char *name,cell val,int index); -constvalue *find_constval(constvalue *table,char *name,int index); -void delete_consttable(constvalue *table); -symbol *add_constant(const char *name,cell val,int vclass,int tag); -void sc_attachdocumentation(symbol *sym); -constvalue *find_tag_byval(int tag); -int get_actual_compound(symbol *sym); - -/* function prototypes in SC2.C */ -#define PUSHSTK_P(v) { stkitem s_; s_.pv=(v); pushstk(s_); } -#define PUSHSTK_I(v) { stkitem s_; s_.i=(v); pushstk(s_); } -#define POPSTK_P() (popstk().pv) -#define POPSTK_I() (popstk().i) -void pushstk(stkitem val); -stkitem popstk(void); -void clearstk(void); -int plungequalifiedfile(char *name); /* explicit path included */ -int plungefile(char *name,int try_currentpath,int try_includepaths); /* search through "include" paths */ -void preprocess(void); -void lexinit(void); -int lex(cell *lexvalue,char **lexsym); -int lextok(token_t *tok); -int lexpeek(int id); -void lexpush(void); -void lexclr(int clreol); -int matchtoken(int token); -int tokeninfo(cell *val,char **str); -int needtoken(int token); -int matchtoken2(int id, token_t *tok); -int expecttoken(int id, token_t *tok); -int matchsymbol(token_ident_t *ident); -int needsymbol(token_ident_t *ident); -int peek_same_line(); -int require_newline(int allow_semi); -void litadd(cell value); -void litinsert(cell value,int pos); -int alphanum(char c); -int ishex(char c); -void delete_symbol(symbol *root,symbol *sym); -void delete_symbols(symbol *root,int level,int del_labels,int delete_functions); -int refer_symbol(symbol *entry,symbol *bywhom); -void markusage(symbol *sym,int usage); -symbol *findglb(const char *name,int filter); -symbol *findloc(const char *name); -symbol *findconst(const char *name,int *matchtag); -symbol *finddepend(const symbol *parent); -symbol *addsym(const char *name,cell addr,int ident,int vclass,int tag, int usage); -symbol *addvariable(const char *name,cell addr,int ident,int vclass,int tag, - int dim[],int numdim,int idxtag[]); -symbol *addvariable2(const char *name,cell addr,int ident,int vclass,int tag, - int dim[],int numdim,int idxtag[],int slength); -symbol *addvariable3(declinfo_t *decl,cell addr,int vclass,int slength); -int getlabel(void); -char *itoh(ucell val); - -#define MATCHTAG_COERCE 0x1 // allow coercion -#define MATCHTAG_SILENT 0x2 // silence the error(213) warning -#define MATCHTAG_COMMUTATIVE 0x4 // order does not matter -#define MATCHTAG_DEDUCE 0x8 // correct coercion - -/* function prototypes in SC3.C */ -int check_userop(void (*oper)(void),int tag1,int tag2,int numparam, - value *lval,int *resulttag); -int matchtag(int formaltag,int actualtag,int allowcoerce); -int checktag(int tags[],int numtags,int exprtag); -int expression(cell *val,int *tag,symbol **symptr,int chkfuncresult,value *_lval); -int sc_getstateid(constvalue **automaton,constvalue **state); -cell array_totalsize(symbol *sym); -int matchtag_string(int ident, int tag); -int checktag_string(value *sym1, value *sym2); -int checktags_string(int tags[], int numtags, value *sym1); -int lvalexpr(svalue *sval); - -/* function prototypes in SC4.C */ -void writeleader(symbol *root); -void writetrailer(void); -void begcseg(void); -void begdseg(void); -void setline(int chkbounds); -void setfiledirect(char *name); -void setlinedirect(int line); -void setlabel(int index); -void markexpr(optmark type,const char *name,cell offset); -void startfunc(char *fname); -void endfunc(void); -void alignframe(int numbytes); -void rvalue(value *lval); -void address(symbol *ptr,regid reg); -void store(value *lval); -void loadreg(cell address,regid reg); -void storereg(cell address,regid reg); -void memcopy(cell size); -void copyarray(symbol *sym,cell size); -void fillarray(symbol *sym,cell size,cell value); -void ldconst(cell val,regid reg); -void moveto1(void); -void move_alt(void); -void pushreg(regid reg); -void pushval(cell val); -void popreg(regid reg); -void genarray(int dims, int _autozero); -void swap1(void); -void ffswitch(int label); -void ffcase(cell value,char *labelname,int newtable); -void ffcall(symbol *sym,const char *label,int numargs); -void ffret(int remparams); -void ffabort(int reason); -void ffbounds(cell size); -void jumplabel(int number); -void defstorage(void); -void modstk(int delta); -void setstk(cell value); -void modheap(int delta); -void modheap_i(); -void setheap_pri(void); -void setheap(cell value); -void cell2addr(void); -void cell2addr_alt(void); -void addr2cell(void); -void char2addr(void); -void charalign(void); -void addconst(cell value); -void setheap_save(cell value); -void stradjust(regid reg); -void invoke_getter(struct methodmap_method_s *method); -void invoke_setter(struct methodmap_method_s *method, int save); -void inc_pri(); -void dec_pri(); -void load_hidden_arg(); -void load_glbfn(symbol *sym); - -/* Code generation functions for arithmetic operators. - * - * Syntax: o[u|s|b]_name - * | | | +--- name of operator - * | | +----- underscore - * | +--------- "u"nsigned operator, "s"igned operator or "b"oth - * +------------- "o"perator - */ -void os_mult(void); /* multiplication (signed) */ -void os_div(void); /* division (signed) */ -void os_mod(void); /* modulus (signed) */ -void ob_add(void); /* addition */ -void ob_sub(void); /* subtraction */ -void ob_sal(void); /* shift left (arithmetic) */ -void os_sar(void); /* shift right (arithmetic, signed) */ -void ou_sar(void); /* shift right (logical, unsigned) */ -void ob_or(void); /* bitwise or */ -void ob_xor(void); /* bitwise xor */ -void ob_and(void); /* bitwise and */ -void ob_eq(void); /* equality */ -void ob_ne(void); /* inequality */ -void relop_prefix(void); -void relop_suffix(void); -void os_le(void); /* less or equal (signed) */ -void os_ge(void); /* greater or equal (signed) */ -void os_lt(void); /* less (signed) */ -void os_gt(void); /* greater (signed) */ - -void lneg(void); -void neg(void); -void invert(void); -void nooperation(void); -void inc(value *lval); -void dec(value *lval); -void jmp_ne0(int number); -void jmp_eq0(int number); -void outval(cell val,int newline); - -/* function prototypes in SC5.C */ -int error(int number,...); -void errorset(int code,int line); - -/* function prototypes in SC6.C */ -void assemble(const char *outname, void *fin); - -/* function prototypes in SC7.C */ -void stgbuffer_cleanup(void); -void stgmark(char mark); -void stgwrite(const char *st); -void stgout(int index); -void stgdel(int index,cell code_index); -int stgget(int *index,cell *code_index); -void stgset(int onoff); -int phopt_init(void); -int phopt_cleanup(void); - -/* function prototypes in SCLIST.C */ -char* duplicatestring(const char* sourcestring); -stringpair *insert_alias(char *name,char *alias); -stringpair *find_alias(char *name); -int lookup_alias(char *target,char *name); -void delete_aliastable(void); -stringlist *insert_path(char *path); -char *get_path(int index); -void delete_pathtable(void); -stringpair *insert_subst(const char *pattern,const char *substitution,int prefixlen); -int get_subst(int index,char **pattern,char **substitution); -stringpair *find_subst(char *name,int length); -int delete_subst(char *name,int length); -void delete_substtable(void); -stringlist *insert_sourcefile(char *string); -char *get_sourcefile(int index); -void delete_sourcefiletable(void); -stringlist *insert_docstring(char *string); -char *get_docstring(int index); -void delete_docstring(int index); -void delete_docstringtable(void); -stringlist *insert_autolist(const char *string); -char *get_autolist(int index); -void delete_autolisttable(void); -stringlist *insert_dbgfile(const char *filename); -stringlist *insert_dbgline(int linenr); -stringlist *insert_dbgsymbol(symbol *sym); -char *get_dbgstring(int index); -void delete_dbgstringtable(void); -stringlist *get_dbgstrings(); - -/* function prototypes in SCI18N.C */ -#define MAXCODEPAGE 12 -int cp_path(const char *root,const char *directory); -int cp_set(const char *name); -cell cp_translate(const unsigned char *string,const unsigned char **endptr); -cell get_utf8_char(const unsigned char *string,const unsigned char **endptr); -int scan_utf8(void *fp,const char *filename); - -/* function prototypes in SCSTATE.C */ -constvalue *automaton_add(const char *name); -constvalue *automaton_find(const char *name); -constvalue *automaton_findid(int id); -constvalue *state_add(const char *name,int fsa_id); -constvalue *state_find(const char *name,int fsa_id); -constvalue *state_findid(int id); -void state_buildlist(int **list,int *listsize,int *count,int stateid); -int state_addlist(int *list,int count,int fsa_id); -void state_deletetable(void); -int state_getfsa(int listid); -int state_count(int listid); -int state_inlist(int listid,int state); -int state_listitem(int listid,int index); -void state_conflict(symbol *root); -int state_conflict_id(int listid1,int listid2); - -/* external variables (defined in scvars.c) */ -#if !defined SC_SKIP_VDECL -typedef struct HashTable HashTable; -extern struct HashTable *sp_Globals; -extern symbol loctab; /* local symbol table */ -extern symbol glbtab; /* global symbol table */ -extern cell *litq; /* the literal queue */ -extern unsigned char pline[]; /* the line read from the input file */ -extern const unsigned char *lptr;/* points to the current position in "pline" */ -extern constvalue tagname_tab;/* tagname table */ -extern constvalue libname_tab;/* library table (#pragma library "..." syntax) */ -extern constvalue *curlibrary;/* current library */ -extern int pc_addlibtable; /* is the library table added to the AMX file? */ -extern symbol *curfunc; /* pointer to current function */ -extern char *inpfname; /* name of the file currently read from */ -extern char outfname[]; /* intermediate (assembler) file name */ -extern char binfname[]; /* binary file name */ -extern char errfname[]; /* error file name */ -extern char sc_ctrlchar; /* the control character (or escape character) */ -extern char sc_ctrlchar_org;/* the default control character */ -extern int litidx; /* index to literal table */ -extern int litmax; /* current size of the literal table */ -extern int stgidx; /* index to the staging buffer */ -extern int sc_labnum; /* number of (internal) labels */ -extern int staging; /* true if staging output */ -extern cell declared; /* number of local cells declared */ -extern cell glb_declared; /* number of global cells declared */ -extern cell code_idx; /* number of bytes with generated code */ -extern int ntv_funcid; /* incremental number of native function */ -extern int errnum; /* number of errors */ -extern int warnnum; /* number of warnings */ -extern int sc_debug; /* debug/optimization options (bit field) */ -extern int sc_packstr; /* strings are packed by default? */ -extern int sc_asmfile; /* create .ASM file? */ -extern int sc_listing; /* create .LST file? */ -extern int sc_compress; /* compress bytecode? */ -extern int sc_needsemicolon;/* semicolon required to terminate expressions? */ -extern int sc_dataalign; /* data alignment value */ -extern int sc_alignnext; /* must frame of the next function be aligned? */ -extern int pc_docexpr; /* must expression be attached to documentation comment? */ -extern int sc_showincludes; /* show include files? */ -extern int curseg; /* 1 if currently parsing CODE, 2 if parsing DATA */ -extern cell pc_stksize; /* stack size */ -extern cell pc_amxlimit; /* abstract machine size limit (code + data, or only code) */ -extern cell pc_amxram; /* abstract machine data size limit */ -extern int freading; /* is there an input file ready for reading? */ -extern int fline; /* the line number in the current file */ -extern short fnumber; /* number of files in the file table (debugging) */ -extern short fcurrent; /* current file being processed (debugging) */ -extern short sc_intest; /* true if inside a test */ -extern int sideeffect; /* true if an expression causes a side-effect */ -extern int stmtindent; /* current indent of the statement */ -extern int indent_nowarn; /* skip warning "217 loose indentation" */ -extern int sc_tabsize; /* number of spaces that a TAB represents */ -extern short sc_allowtags; /* allow/detect tagnames in lex() */ -extern int sc_status; /* read/write status */ -extern int sc_err_status; /* TRUE if errors should be generated even if sc_status = SKIP */ -extern int sc_rationaltag; /* tag for rational numbers */ -extern int rational_digits; /* number of fractional digits */ -extern int sc_allowproccall;/* allow/detect tagnames in lex() */ -extern short sc_is_utf8; /* is this source file in UTF-8 encoding */ -extern char *pc_deprecate; /* if non-NULL, mark next declaration as deprecated */ -extern int sc_curstates; /* ID of the current state list */ -extern int pc_optimize; /* (peephole) optimization level */ -extern int pc_memflags; /* special flags for the stack/heap usage */ -extern int pc_functag; /* global function tag */ -extern int pc_tag_string; /* global String tag */ -extern int pc_tag_void; /* global void tag */ -extern int pc_tag_object; /* root object tag */ -extern int pc_tag_bool; /* global bool tag */ -extern int pc_tag_null_t; /* the null type */ -extern int pc_tag_nullfunc_t; /* the null function type */ -extern int pc_anytag; /* global any tag */ -extern int glbstringread; /* last global string read */ -extern int sc_require_newdecls; /* only newdecls are allowed */ -extern bool sc_warnings_are_errors; - -extern constvalue sc_automaton_tab; /* automaton table */ -extern constvalue sc_state_tab; /* state table */ - -extern void *inpf; /* file read from (source or include) */ -extern void *inpf_org; /* main source file */ -extern void *outf; /* file written to */ - -extern jmp_buf errbuf; /* target of longjmp() on a fatal error */ - -#if !defined SC_LIGHT - extern int sc_makereport; /* generate a cross-reference report */ -#endif - -#if defined WIN32 -# if !defined snprintf -# define snprintf _snprintf -# define vsnprintf _vsnprintf -# endif -#endif - -#endif /* SC_SKIP_VDECL */ - -typedef struct array_info_s -{ - const int *dim_list; /* Dimension sizes */ - int dim_count; /* Number of dimensions */ - const int *lastdim_list; /* Sizes of last dimensions, if variable */ - const cell *dim_offs_precalc; /* Cached calculations into the lastdim_list array */ - cell *data_offs; /* Current offset AFTER the indirection vectors (data) */ - int *cur_dims; /* Current dimensions the recursion is at */ - cell *base; /* &litq[startlit] */ -} array_info_t; - -enum FatalError { - FIRST_FATAL_ERROR = 183, - - FATAL_ERROR_READ = FIRST_FATAL_ERROR, - FATAL_ERROR_WRITE, - FATAL_ERROR_ALLOC_OVERFLOW, - FATAL_ERROR_OOM, - FATAL_ERROR_INVALID_INSN, - FATAL_ERROR_INT_OVERFLOW, - FATAL_ERROR_SCRIPT_OVERFLOW, - FATAL_ERROR_OVERWHELMED_BY_BAD, - FATAL_ERROR_NO_CODEPAGE, - FATAL_ERROR_INVALID_PATH, - FATAL_ERROR_ASSERTION_FAILED, - FATAL_ERROR_USER_ERROR, - - FATAL_ERRORS_TOTAL -}; - -struct AutoDisableLiteralQueue -{ - public: - AutoDisableLiteralQueue(); - ~AutoDisableLiteralQueue(); - - private: - bool prev_value_; -}; - -#endif /* SC_H_INCLUDED */ diff --git a/sourcepawn/compiler/sc1.cpp b/sourcepawn/compiler/sc1.cpp deleted file mode 100644 index 9e74e96b..00000000 --- a/sourcepawn/compiler/sc1.cpp +++ /dev/null @@ -1,7955 +0,0 @@ -/* vim: set sts=2 ts=8 sw=2 tw=99 et: */ -/* Pawn compiler - * - * Function and variable definition and declaration, statement parser. - * - * Copyright (c) ITB CompuPhase, 1997-2006 - * - * This software is provided "as-is", without any express or implied warranty. - * In no event will the authors be held liable for any damages arising from - * the use of this software. - * - * Permission is granted to anyone to use this software for any purpose, - * including commercial applications, and to alter it and redistribute it - * freely, subject to the following restrictions: - * - * 1. The origin of this software must not be misrepresented; you must not - * claim that you wrote the original software. If you use this software in - * a product, an acknowledgment in the product documentation would be - * appreciated but is not required. - * 2. Altered source versions must be plainly marked as such, and must not be - * misrepresented as being the original software. - * 3. This notice may not be removed or altered from any source distribution. - * - * Version: $Id$ - */ -#include -#include -#include -#include -#include -#include -#include - -#if defined __WIN32__ || defined _WIN32 || defined __MSDOS__ - #include - #include -#endif - -#if defined LINUX || defined __FreeBSD__ || defined __OpenBSD__ || defined DARWIN - #include "sclinux.h" - #include "binreloc.h" /* from BinReloc, see www.autopackage.org */ - #include -#endif - -#if defined FORTIFY - #include -#endif - -#if defined __BORLANDC__ || defined __WATCOMC__ - #include - static unsigned total_drives; /* dummy variable */ - #define dos_setdrive(i) _dos_setdrive(i,&total_drives) -#elif defined _MSC_VER && defined _WIN32 - #include /* for _chdrive() */ - #define dos_setdrive(i) _chdrive(i) -#endif -#if defined __BORLANDC__ - #include /* for chdir() */ -#elif defined __WATCOMC__ - #include /* for chdir() */ -#endif -#if defined __WIN32__ || defined _WIN32 || defined _Windows - #include -#endif - -#include - -#include "lstring.h" -#include "sc.h" -#include -#include "sctracker.h" -#include "sp_symhash.h" -#define VERSION_STR "3.2.3636" -#define VERSION_INT 0x0302 - -int pc_anytag = 0; -int pc_functag = 0; -int pc_tag_string = 0; -int pc_tag_void = 0; -int pc_tag_object = 0; -int pc_tag_bool = 0; -int pc_tag_null_t = 0; -int pc_tag_nullfunc_t = 0; - -static void resetglobals(void); -static void initglobals(void); -static char *get_extension(char *filename); -static void setopt(int argc,char **argv,char *oname,char *ename,char *pname, - char *rname,char *codepage); -static void setconfig(char *root); -static void setcaption(void); -static void about(void); -static void setconstants(void); -static void parse(void); -static void dumplits(void); -static void dumpzero(int count); -static void declglb(declinfo_t *decl,int fpublic,int fstatic,int stock); -static void declstructvar(char *firstname,int fpublic, pstruct_t *pstruct); -static void declloc(int tokid); -static void dodelete(); -static void decl_const(int table); -static void declstruct(); -static void decl_enum(int table); -static cell needsub(int *tag,constvalue **enumroot); -static void initials(int ident,int tag,cell *size,int dim[],int numdim, - constvalue *enumroot); -static cell initarray(int ident,int tag,int dim[],int numdim,int cur, - int startlit,int counteddim[],constvalue *lastdim, - constvalue *enumroot,int *errorfound); -static cell initvector(int ident,int tag,cell size,int fillzero, - constvalue *enumroot,int *errorfound); -static void initials3(declinfo_t *decl); -static cell fix_char_size(declinfo_t *decl); -static cell init(int ident,int *tag,int *errorfound); -static int getstates(const char *funcname); -static void attachstatelist(symbol *sym, int state_id); -static symbol *funcstub(int tokid, declinfo_t *decl, const int *thistag); -static int newfunc(declinfo_t *decl, const int *thistag, int fpublic, int fstatic, int stock, symbol **symp); -static int declargs(symbol *sym, int chkshadow, const int *thistag); -static void doarg(declinfo_t *decl, int offset, int fpublic, int chkshadow, arginfo *arg); -static void make_report(symbol *root,FILE *log,char *sourcefile); -static void reduce_referrers(symbol *root); -static long max_stacksize(symbol *root,int *recursion); -static int testsymbols(symbol *root,int level,int testlabs,int testconst); -static void destructsymbols(symbol *root,int level); -static constvalue *find_constval_byval(constvalue *table,cell val); -static symbol *fetchlab(char *name); -static void statement(int *lastindent,int allow_decl); -static void compound(int stmt_sameline,int starttok); -static int test(int label,int parens,int invert); -static int doexpr(int comma,int chkeffect,int allowarray,int mark_endexpr, - int *tag,symbol **symptr,int chkfuncresult); -static int doexpr2(int comma,int chkeffect,int allowarray,int mark_endexpr, - int *tag,symbol **symptr,int chkfuncresult,value *lval); -static void doassert(void); -static void doexit(void); -static int doif(void); -static int dowhile(void); -static int dodo(void); -static int dofor(void); -static void doswitch(void); -static void dogoto(void); -static void dolabel(void); -static void doreturn(void); -static void dofuncenum(int listmode); -static void dotypedef(); -static void dotypeset(); -static void domethodmap(LayoutSpec spec); -static void dobreak(void); -static void docont(void); -static void dosleep(void); -static void dostate(void); -static void addwhile(int *ptr); -static void delwhile(void); -static int *readwhile(void); -static void inst_datetime_defines(void); -static void inst_binary_name(char *binfname); -static int operatorname(char *name); -static int parse_new_typename(const token_t *tok); -static int parse_new_decl(declinfo_t *decl, const token_t *first, int flags); -static int reparse_old_decl(declinfo_t *decl, int flags); -static int reparse_new_decl(declinfo_t *decl, int flags); -static void check_void_decl(const declinfo_t *decl, int variable); - -enum { - TEST_PLAIN, /* no parentheses */ - TEST_THEN, /* '(' ')' or 'then' */ - TEST_DO, /* '(' ')' or 'do' */ - TEST_OPT, /* '(' ')' or */ -}; -static int norun = 0; /* the compiler never ran */ -static int autozero = 1; /* if 1 will zero out the variable, if 0 omit the zeroing */ -static int lastst = 0; /* last executed statement type */ -static int nestlevel = 0; /* number of active (open) compound statements */ -static int endlessloop= 0; /* nesting level of endless loop */ -static int rettype = 0; /* the type that a "return" expression should have */ -static int skipinput = 0; /* number of lines to skip from the first input file */ -static int optproccall = TRUE; /* support "procedure call" */ -static int verbosity = 1; /* verbosity level, 0=quiet, 1=normal, 2=verbose */ -static int sc_reparse = 0; /* needs 3th parse because of changed prototypes? */ -static int sc_parsenum = 0; /* number of the extra parses */ -static int wq[wqTABSZ]; /* "while queue", internal stack for nested loops */ -static int *wqptr; /* pointer to next entry */ -#if !defined SC_LIGHT - static char sc_rootpath[_MAX_PATH]; - static char *sc_documentation=NULL;/* main documentation */ -#endif -#if defined __WIN32__ || defined _WIN32 || defined _Windows - static HWND hwndFinish = 0; -#endif - -int glbstringread = 0; -char g_tmpfile[_MAX_PATH] = {0}; - -/* "main" of the compiler - */ -int pc_compile(int argc, char *argv[]) -{ - int entry,i,jmpcode; - int retcode; - char incfname[_MAX_PATH]; - char reportname[_MAX_PATH]; - char codepage[MAXCODEPAGE+1]; - void *inpfmark; - int lcl_packstr,lcl_needsemicolon,lcl_tabsize,lcl_require_newdecls; - char *ptr; - - /* set global variables to their initial value */ - initglobals(); - errorset(sRESET,0); - errorset(sEXPRRELEASE,0); - lexinit(); - - /* make sure that we clean up on a fatal error; do this before the first - * call to error(). */ - if ((jmpcode=setjmp(errbuf))!=0) - goto cleanup; - - sp_Globals = NewHashTable(); - if (!sp_Globals) - error(FATAL_ERROR_OOM); - - /* allocate memory for fixed tables */ - inpfname=(char*)malloc(_MAX_PATH); - if (inpfname==NULL) - error(FATAL_ERROR_OOM); /* insufficient memory */ - litq=(cell*)malloc(litmax*sizeof(cell)); - if (litq==NULL) - error(FATAL_ERROR_OOM); /* insufficient memory */ - if (!phopt_init()) - error(FATAL_ERROR_OOM); /* insufficient memory */ - - setopt(argc,argv,outfname,errfname,incfname,reportname,codepage); - strcpy(binfname,outfname); - ptr=get_extension(binfname); - if (ptr!=NULL && stricmp(ptr,".asm")==0) - set_extension(binfname,".smx",TRUE); - else - set_extension(binfname,".smx",FALSE); - /* set output names that depend on the input name */ - if (sc_listing) - set_extension(outfname,".lst",TRUE); - else - set_extension(outfname,".asm",TRUE); - if (strlen(errfname)!=0) - remove(errfname); /* delete file on startup */ - else if (verbosity>0) - setcaption(); - setconfig(argv[0]); /* the path to the include and codepage files */ - sc_ctrlchar_org=sc_ctrlchar; - lcl_packstr=sc_packstr; - lcl_needsemicolon=sc_needsemicolon; - lcl_require_newdecls=sc_require_newdecls; - lcl_tabsize=sc_tabsize; - #if !defined NO_CODEPAGE - if (!cp_set(codepage)) /* set codepage */ - error(FATAL_ERROR_NO_CODEPAGE); - #endif - /* optionally create a temporary input file that is a collection of all - * input files - */ - assert(get_sourcefile(0)!=NULL); /* there must be at least one source file */ - if (get_sourcefile(1)!=NULL) { - /* there are at least two or more source files */ - char *tname,*sname; - void *ftmp,*fsrc; - int fidx; - #if defined __WIN32__ || defined _WIN32 - tname=_tempnam(NULL,"pawn"); - #elif defined __MSDOS__ || defined _Windows - tname=tempnam(NULL,"pawn"); - #elif defined(MACOS) && !defined(__MACH__) - /* tempnam is not supported for the Macintosh CFM build. */ - error(FATAL_ERROR_INVALID_INSN,get_sourcefile(1)); - tname=NULL; - sname=NULL; - #else - char *buffer = strdup(P_tmpdir "/pawn.XXXXXX"); - close(mkstemp(buffer)); - tname=buffer; - #endif - ftmp=pc_createsrc(tname); - for (fidx=0; (sname=get_sourcefile(fidx))!=NULL; fidx++) { - unsigned char tstring[128]; - fsrc=pc_opensrc(sname); - if (fsrc==NULL) { - pc_closesrc(ftmp); - remove(tname); - strcpy(inpfname,sname); /* avoid invalid filename */ - error(FATAL_ERROR_READ,sname); - } /* if */ - pc_writesrc(ftmp,(unsigned char*)"#file \""); - pc_writesrc(ftmp,(unsigned char*)sname); - pc_writesrc(ftmp,(unsigned char*)"\"\n"); - while (!pc_eofsrc(fsrc) && pc_readsrc(fsrc,tstring,sizeof tstring)) { - pc_writesrc(ftmp,tstring); - } /* while */ - pc_closesrc(fsrc); - } /* for */ - pc_closesrc(ftmp); - strcpy(inpfname,tname); - strcpy(g_tmpfile,tname); - free(tname); - } else { - strcpy(inpfname,get_sourcefile(0)); - } /* if */ - inpf_org=pc_opensrc(inpfname); - if (inpf_org==NULL) - error(FATAL_ERROR_READ,inpfname); - freading=TRUE; - outf=(FILE*)pc_openasm(outfname); /* first write to assembler file (may be temporary) */ - if (outf==NULL) - error(FATAL_ERROR_WRITE,outfname); - setconstants(); /* set predefined constants and tagnames */ - for (i=0; i0) { - if (strcmp(incfname,sDEF_PREFIX)==0) { - plungefile(incfname,FALSE,TRUE); /* parse "default.inc" */ - } else { - if (!plungequalifiedfile(incfname)) /* parse "prefix" include file */ - error(FATAL_ERROR_READ,incfname); - } /* if */ - } /* if */ - preprocess(); /* fetch first line */ - parse(); /* process all input */ - sc_parsenum++; - } while (sc_reparse); - - /* second (or third) pass */ - sc_status=statWRITE; /* set, to enable warnings */ - state_conflict(&glbtab); - - /* write a report, if requested */ - #if !defined SC_LIGHT - if (sc_makereport) { - FILE *frep=stdout; - if (strlen(reportname)>0) - frep=fopen(reportname,"wb"); /* avoid translation of \n to \r\n in DOS/Windows */ - if (frep!=NULL) { - make_report(&glbtab,frep,get_sourcefile(0)); - if (strlen(reportname)>0) - fclose(frep); - } /* if */ - if (sc_documentation!=NULL) { - free(sc_documentation); - sc_documentation=NULL; - } /* if */ - } /* if */ - #endif - if (sc_listing) - goto cleanup; - - /* ??? for re-parsing the listing file instead of the original source - * file (and doing preprocessing twice): - * - close input file, close listing file - * - re-open listing file for reading (inpf) - * - open assembler file (outf) - */ - - /* reset "defined" flag of all functions and global variables */ - reduce_referrers(&glbtab); - delete_symbols(&glbtab,0,TRUE,FALSE); - funcenums_free(); - methodmaps_free(); - pstructs_free(); - #if !defined NO_DEFINE - delete_substtable(); - inst_datetime_defines(); - inst_binary_name(binfname); - #endif - resetglobals(); - sc_ctrlchar=sc_ctrlchar_org; - sc_packstr=lcl_packstr; - sc_needsemicolon=lcl_needsemicolon; - sc_require_newdecls=lcl_require_newdecls; - sc_tabsize=lcl_tabsize; - errorset(sRESET,0); - /* reset the source file */ - inpf=inpf_org; - freading=TRUE; - pc_resetsrc(inpf,inpfmark); /* reset file position */ - fline=skipinput; /* reset line number */ - lexinit(); /* clear internal flags of lex() */ - sc_status=statWRITE; /* allow to write --this variable was reset by resetglobals() */ - writeleader(&glbtab); - insert_dbgfile(inpfname); - if (strlen(incfname)>0) { - if (strcmp(incfname,sDEF_PREFIX)==0) - plungefile(incfname,FALSE,TRUE); /* parse "default.inc" (again) */ - else - plungequalifiedfile(incfname); /* parse implicit include file (again) */ - } /* if */ - preprocess(); /* fetch first line */ - parse(); /* process all input */ - /* inpf is already closed when readline() attempts to pop of a file */ - writetrailer(); /* write remaining stuff */ - - entry=testsymbols(&glbtab,0,TRUE,FALSE); /* test for unused or undefined - * functions and variables */ - if (!entry) - error(13); /* no entry point (no public functions) */ - -cleanup: - if (inpf!=NULL) /* main source file is not closed, do it now */ - pc_closesrc(inpf); - - // Write the binary file. - if (!(sc_asmfile || sc_listing) && errnum==0 && jmpcode==0) { - pc_resetasm(outf); - assemble(binfname, outf); - } - - if (outf!=NULL) { - pc_closeasm(outf,!(sc_asmfile || sc_listing)); - outf=NULL; - } /* if */ - -#if !defined SC_LIGHT - if (errnum==0 && strlen(errfname)==0) { -# if 0 //bug in compiler -- someone's script caused this function to infrecurs - int recursion; - long stacksize=max_stacksize(&glbtab,&recursion); -# endif - int flag_exceed=0; - if (pc_amxlimit>0) { - long totalsize=code_idx; - if (pc_amxram==0) - totalsize+=(glb_declared+pc_stksize)*sizeof(cell); - if (totalsize>=pc_amxlimit) - flag_exceed=1; - } /* if */ - if (pc_amxram>0 && (glb_declared+pc_stksize)*sizeof(cell)>=(unsigned long)pc_amxram) - flag_exceed=1; - if ((!norun && (sc_debug & sSYMBOLIC)!=0) || verbosity>=2 || flag_exceed) { - pc_printf("Code size: %8ld bytes\n", (long)code_idx); - pc_printf("Data size: %8ld bytes\n", (long)glb_declared*sizeof(cell)); - pc_printf("Stack/heap size: %8ld bytes\n", (long)pc_stksize*sizeof(cell)); - pc_printf("Total requirements:%8ld bytes\n", (long)code_idx+(long)glb_declared*sizeof(cell)+(long)pc_stksize*sizeof(cell)); - } /* if */ - if (flag_exceed) - error(FATAL_ERROR_INT_OVERFLOW,pc_amxlimit+pc_amxram); /* this causes a jump back to label "cleanup" */ - } /* if */ - #endif - - if (g_tmpfile[0] != '\0') { - remove(g_tmpfile); - } - if (inpfname!=NULL) { - free(inpfname); - } /* if */ - if (litq!=NULL) - free(litq); - phopt_cleanup(); - stgbuffer_cleanup(); - clearstk(); - assert(jmpcode!=0 || loctab.next==NULL);/* on normal flow, local symbols - * should already have been deleted */ - delete_symbols(&loctab,0,TRUE,TRUE); /* delete local variables if not yet - * done (i.e. on a fatal error) */ - delete_symbols(&glbtab,0,TRUE,TRUE); - DestroyHashTable(sp_Globals); - delete_consttable(&tagname_tab); - delete_consttable(&libname_tab); - delete_consttable(&sc_automaton_tab); - delete_consttable(&sc_state_tab); - state_deletetable(); - delete_aliastable(); - delete_pathtable(); - delete_sourcefiletable(); - delete_dbgstringtable(); - funcenums_free(); - methodmaps_free(); - pstructs_free(); - #if !defined NO_DEFINE - delete_substtable(); - #endif - #if !defined SC_LIGHT - delete_docstringtable(); - if (sc_documentation!=NULL) - free(sc_documentation); - #endif - delete_autolisttable(); - if (errnum!=0) { - if (strlen(errfname)==0) - pc_printf("\n%d Error%s.\n",errnum,(errnum>1) ? "s" : ""); - retcode=1; - } else if (warnnum!=0){ - if (strlen(errfname)==0) - pc_printf("\n%d Warning%s.\n",warnnum,(warnnum>1) ? "s" : ""); - retcode=0; /* use "0", so that MAKE and similar tools continue */ - } else { - retcode=jmpcode; - if (retcode==0 && verbosity>=2) - pc_printf("\nDone.\n"); - } /* if */ - #if defined __WIN32__ || defined _WIN32 || defined _Windows - if (IsWindow(hwndFinish)) - PostMessageA(hwndFinish,RegisterWindowMessageA("PawnNotify"),retcode,0L); - #endif - #if defined FORTIFY - Fortify_ListAllMemory(); - #endif - return retcode; -} - -int pc_addconstant(const char *name,cell value,int tag) -{ - errorset(sFORCESET,0); /* make sure error engine is silenced */ - sc_status=statIDLE; - add_constant(name,value,sGLOBAL,tag); - return 1; -} - -static void inst_binary_name(char *binfname) -{ - size_t i, len; - char *binptr; - char newpath[512], newname[512]; - - binptr = NULL; - len = strlen(binfname); - for (i = len - 1; i < len; i--) - { - if (binfname[i] == '/' -#if defined WIN32 || defined _WIN32 - || binfname[i] == '\\' -#endif - ) - { - binptr = &binfname[i + 1]; - break; - } - } - - if (binptr == NULL) - { - binptr = binfname; - } - - snprintf(newpath, sizeof(newpath), "\"%s\"", binfname); - snprintf(newname, sizeof(newname), "\"%s\"", binptr); - - insert_subst("__BINARY_PATH__", newpath, 15); - insert_subst("__BINARY_NAME__", newname, 15); -} - -static void inst_datetime_defines(void) -{ - char date[64]; - char ltime[64]; - time_t td; - struct tm *curtime; - - time(&td); - curtime = localtime(&td); - -#if defined EMSCRIPTEN - snprintf(date, sizeof(date), "\"%02d/%02d/%04d\"", curtime->tm_mon + 1, curtime->tm_mday, curtime->tm_year + 1900); - snprintf(ltime, sizeof(ltime), "\"%02d:%02d:%02d\"", curtime->tm_hour, curtime->tm_min, curtime->tm_sec); -#else - strftime(date, 31, "\"%m/%d/%Y\"", curtime); - strftime(ltime, 31, "\"%H:%M:%S\"", curtime); -#endif - - insert_subst("__DATE__", date, 8); - insert_subst("__TIME__", ltime, 8); -} - -const char *pc_typename(int tag) -{ - if (tag == 0) - return "int"; - if (tag == sc_rationaltag) - return "float"; - if (tag == pc_tag_string) - return "char"; - return pc_tagname(tag); -} - -const char *pc_tagname(int tag) -{ - constvalue *ptr=tagname_tab.next; - for (; ptr; ptr=ptr->next) { - if (TAGID(ptr->value) == TAGID(tag)) - return ptr->name; - } - return "__unknown__"; -} - -constvalue *pc_tagptr(const char *name) -{ - constvalue *ptr=tagname_tab.next; - for (; ptr; ptr=ptr->next) { - if (strcmp(name, ptr->name)==0) - return ptr; - } - return NULL; -} - -int pc_findtag(const char *name) -{ - constvalue *ptr=tagname_tab.next; - for (; ptr; ptr=ptr->next) { - if (strcmp(name,ptr->name)==0) - return ptr->value; - } - return -1; -} - -int pc_addtag(const char *name) -{ - int val; - int flags = 0; - - if (name==NULL) { - /* no tagname was given, check for one */ - char *nameptr; - if (lex(&val,&nameptr)!=tLABEL) { - lexpush(); - return 0; /* untagged */ - } /* if */ - name = nameptr; - } /* if */ - - if (isupper(*name)) - flags |= FIXEDTAG; - - return pc_addtag_flags(name, flags); -} - -int pc_addtag_flags(const char *name, int flags) -{ - constvalue *ptr; - int last; - - assert((flags & FUNCTAG) || strchr(name,':')==NULL); /* colon should already have been stripped */ - last=0; - ptr=tagname_tab.next; - while (ptr!=NULL) { - if (strcmp(name,ptr->name)==0) { - // Update the flag set. - ptr->value |= flags; - return ptr->value; - } - if (TAGID(ptr->value) > last) - last = TAGID(ptr->value); - ptr = ptr->next; - } /* while */ - - /* tagname currently unknown, add it */ - int tag = (last + 1) | flags; - append_constval(&tagname_tab, name, (cell)tag, 0); - return tag; -} - -static void resetglobals(void) -{ - /* reset the subset of global variables that is modified by the first pass */ - curfunc=NULL; /* pointer to current function */ - lastst=0; /* last executed statement type */ - nestlevel=0; /* number of active (open) compound statements */ - rettype=0; /* the type that a "return" expression should have */ - litidx=0; /* index to literal table */ - stgidx=0; /* index to the staging buffer */ - sc_labnum=0; /* top value of (internal) labels */ - staging=0; /* true if staging output */ - declared=0; /* number of local cells declared */ - glb_declared=0; /* number of global cells declared */ - code_idx=0; /* number of bytes with generated code */ - ntv_funcid=0; /* incremental number of native function */ - curseg=0; /* 1 if currently parsing CODE, 2 if parsing DATA */ - freading=FALSE; /* no input file ready yet */ - fline=0; /* the line number in the current file */ - fnumber=0; /* the file number in the file table (debugging) */ - fcurrent=0; /* current file being processed (debugging) */ - sc_intest=FALSE; /* true if inside a test */ - sideeffect=0; /* true if an expression causes a side-effect */ - stmtindent=0; /* current indent of the statement */ - indent_nowarn=FALSE; /* do not skip warning "217 loose indentation" */ - sc_allowtags=TRUE; /* allow/detect tagnames */ - sc_status=statIDLE; - sc_allowproccall=FALSE; - pc_addlibtable=TRUE; /* by default, add a "library table" to the output file */ - sc_alignnext=FALSE; - pc_docexpr=FALSE; - pc_deprecate=NULL; - sc_curstates=0; - pc_memflags=0; -} - -static void initglobals(void) -{ - resetglobals(); - - sc_asmfile=FALSE; /* do not create .ASM file */ - sc_listing=FALSE; /* do not create .LST file */ - skipinput=0; /* number of lines to skip from the first input file */ - sc_ctrlchar=CTRL_CHAR;/* the escape character */ - litmax=sDEF_LITMAX; /* current size of the literal table */ - errnum=0; /* number of errors */ - warnnum=0; /* number of warnings */ - optproccall=FALSE; /* sourcemod: do not support "procedure call" */ - verbosity=1; /* verbosity level, no copyright banner */ - sc_debug=sCHKBOUNDS|sSYMBOLIC; /* sourcemod: full debug stuff */ - pc_optimize=sOPTIMIZE_DEFAULT; /* sourcemod: full optimization */ - sc_packstr=TRUE; /* strings are packed by default */ - sc_compress=FALSE; /* always disable compact encoding! */ - sc_needsemicolon=FALSE;/* semicolon required to terminate expressions? */ - sc_require_newdecls = FALSE; - sc_dataalign=sizeof(cell); - pc_stksize=sDEF_AMXSTACK;/* default stack size */ - pc_amxlimit=0; /* no limit on size of the abstract machine */ - pc_amxram=0; /* no limit on data size of the abstract machine */ - sc_tabsize=8; /* assume a TAB is 8 spaces */ - sc_rationaltag=0; /* assume no support for rational numbers */ - rational_digits=0; /* number of fractional digits */ - - outfname[0]='\0'; /* output file name */ - errfname[0]='\0'; /* error file name */ - inpf=NULL; /* file read from */ - inpfname=NULL; /* pointer to name of the file currently read from */ - outf=NULL; /* file written to */ - litq=NULL; /* the literal queue */ - glbtab.next=NULL; /* clear global variables/constants table */ - loctab.next=NULL; /* " local " / " " */ - tagname_tab.next=NULL;/* tagname table */ - libname_tab.next=NULL;/* library table (#pragma library "..." syntax) */ - - pline[0]='\0'; /* the line read from the input file */ - lptr=NULL; /* points to the current position in "pline" */ - curlibrary=NULL; /* current library */ - inpf_org=NULL; /* main source file */ - - wqptr=wq; /* initialize while queue pointer */ - -#if !defined SC_LIGHT - sc_documentation=NULL; - sc_makereport=FALSE; /* do not generate a cross-reference report */ -#endif -} - -static char *get_extension(char *filename) -{ - char *ptr; - - assert(filename!=NULL); - ptr=strrchr(filename,'.'); - if (ptr!=NULL) { - /* ignore extension on a directory or at the start of the filename */ - if (strchr(ptr,DIRSEP_CHAR)!=NULL || ptr==filename || *(ptr-1)==DIRSEP_CHAR) - ptr=NULL; - } /* if */ - return ptr; -} - -/* set_extension - * Set the default extension, or force an extension. To erase the - * extension of a filename, set "extension" to an empty string. - */ -void set_extension(char *filename,const char *extension,int force) -{ - char *ptr; - - assert(extension!=NULL && (*extension=='\0' || *extension=='.')); - assert(filename!=NULL); - ptr=get_extension(filename); - if (force && ptr!=NULL) - *ptr='\0'; /* set zero terminator at the position of the period */ - if (force || ptr==NULL) - strcat(filename,extension); -} - -static const char *option_value(const char *optptr,char **argv,int argc,int *arg) -{ - const char *ptr; - - if (*(optptr+1)=='=' || *(optptr+1)==':') - ptr=optptr+2; - else - ptr=optptr+1; - - if (strlen(ptr)==0 && *arg!=argc-1) - ptr=argv[++*arg]; - - return ptr; -} - -static int toggle_option(const char *optptr,int option) -{ - switch ((*(optptr+1)=='=' || *(optptr+1)==':') ? *(optptr+2) : *(optptr+1)) { - case '-': - option=FALSE; - break; - case '+': - option=TRUE; - break; - default: - about(); - } /* switch */ - return option; -} - -/* Parsing command line options is indirectly recursive: parseoptions() - * calls parserespf() to handle options in a a response file and - * parserespf() calls parseoptions() at its turn after having created - * an "option list" from the contents of the file. - */ -static void parserespf(char *filename,char *oname,char *ename,char *pname, - char *rname, char *codepage); - -static void parseoptions(int argc,char **argv,char *oname,char *ename,char *pname, - char *rname, char *codepage) -{ - char str[_MAX_PATH],*name; - const char *ptr; - int arg,i,isoption; - - for (arg=1; arg1) - verbosity=1; - break; -#if 0 /* not allowed in SourceMod */ - case 'C': - #if AMX_COMPACTMARGIN > 2 - sc_compress=toggle_option(ptr,sc_compress); - #else - about(); - #endif - break; -#endif - case 'c': - strlcpy(codepage,option_value(ptr,argv,argc,&arg),MAXCODEPAGE); /* set name of codepage */ - break; -#if defined dos_setdrive - case 'D': /* set active directory */ - ptr=option_value(ptr,argv,argc,&arg); - if (ptr[1]==':') - dos_setdrive(toupper(*ptr)-'A'+1); /* set active drive */ - chdir(ptr); - break; -#endif -#if 0 /* not allowed to change for SourceMod */ - case 'd': - switch (*option_value(ptr,argv,argc,&arg)) { - case '0': - sc_debug=0; - break; - case '1': - sc_debug=sCHKBOUNDS; /* assertions and bounds checking */ - break; - case '2': - sc_debug=sCHKBOUNDS | sSYMBOLIC; /* also symbolic info */ - break; - case '3': - sc_debug=sCHKBOUNDS | sSYMBOLIC; - pc_optimize=sOPTIMIZE_NONE; - /* also avoid peephole optimization */ - break; - default: - about(); - } /* switch */ - break; -#endif - case 'e': - strlcpy(ename,option_value(ptr,argv,argc,&arg),_MAX_PATH); /* set name of error file */ - break; - case 'E': - sc_warnings_are_errors = true; - break; -#if defined __WIN32__ || defined _WIN32 || defined _Windows - case 'H': - hwndFinish=(HWND)atoi(option_value(ptr,argv,argc,&arg)); - if (!IsWindow(hwndFinish)) - hwndFinish=(HWND)0; - break; -#endif - case 'h': - sc_showincludes = 1; - break; - case 'i': - strlcpy(str,option_value(ptr,argv,argc,&arg),sizeof str); /* set name of include directory */ - i=strlen(str); - if (i>0) { - if (str[i-1]!=DIRSEP_CHAR) { - str[i]=DIRSEP_CHAR; - str[i+1]='\0'; - } /* if */ - insert_path(str); - } /* if */ - break; - case 'l': - if (*(ptr+1)!='\0') - about(); - sc_listing=TRUE; /* skip second pass & code generation */ - break; - case 'o': - strlcpy(oname,option_value(ptr,argv,argc,&arg),_MAX_PATH); /* set name of (binary) output file */ - break; - case 'O': - pc_optimize=*option_value(ptr,argv,argc,&arg) - '0'; - if (pc_optimize=sOPTIMIZE_NUMBER || pc_optimize==sOPTIMIZE_NOMACRO) - about(); - break; - case 'p': - strlcpy(pname,option_value(ptr,argv,argc,&arg),_MAX_PATH); /* set name of implicit include file */ - break; -#if !defined SC_LIGHT - case 'r': - strlcpy(rname,option_value(ptr,argv,argc,&arg),_MAX_PATH); /* set name of report file */ - sc_makereport=TRUE; -#if 0 /* dead code due to option_value change to allow spaces between option and value */ - if (strlen(rname)>0) { - set_extension(rname,".xml",FALSE); - } else if ((name=get_sourcefile(0))!=NULL) { - assert(strlen(rname)==0); - assert(strlen(name)<_MAX_PATH); - if ((ptr=strrchr(name,DIRSEP_CHAR))!=NULL) - ptr++; /* strip path */ - else - ptr=name; - assert(strlen(ptr)<_MAX_PATH); - strcpy(rname,ptr); - set_extension(rname,".xml",TRUE); - } /* if */ -#endif - break; -#endif - case 'S': - i=atoi(option_value(ptr,argv,argc,&arg)); - if (i>32) - pc_stksize=(cell)i; /* stack size has minimum size */ - else - about(); - break; - case 's': - skipinput=atoi(option_value(ptr,argv,argc,&arg)); - break; - case 't': - sc_tabsize=atoi(option_value(ptr,argv,argc,&arg)); - break; - case 'v': - verbosity= isdigit(*option_value(ptr,argv,argc,&arg)) ? atoi(option_value(ptr,argv,argc,&arg)) : 2; - if (sc_asmfile && verbosity>1) - verbosity=1; - break; - case 'w': - i=(int)strtol(option_value(ptr,argv,argc,&arg),(char **)&ptr,10); - if (*ptr=='-') - pc_enablewarning(i,0); - else if (*ptr=='+') - pc_enablewarning(i,1); - else if (*ptr=='\0') - pc_enablewarning(i,2); - break; - case 'X': - if (*(ptr+1)=='D') { - i=atoi(option_value(ptr+1,argv,argc,&arg)); - if (i>64) - pc_amxram=(cell)i; /* abstract machine data/stack has minimum size */ - else - about(); - } else { - i=atoi(option_value(ptr,argv,argc,&arg)); - if (i>64) - pc_amxlimit=(cell)i;/* abstract machine has minimum size */ - else - about(); - } /* if */ - break; - case '\\': /* use \ instead for escape characters */ - sc_ctrlchar='\\'; - break; - case '^': /* use ^ instead for escape characters */ - sc_ctrlchar='^'; - break; - case ';': - sc_needsemicolon=toggle_option(ptr,sc_needsemicolon); - break; -#if 0 /* not allowed to change in SourceMod */ - case '(': - optproccall=!toggle_option(ptr,!optproccall); - break; -#endif - default: /* wrong option */ - about(); - } /* switch */ - } else if (argv[arg][0]=='@') { - #if !defined SC_LIGHT - parserespf(&argv[arg][1],oname,ename,pname,rname,codepage); - #endif - } else if ((ptr=strchr(argv[arg],'='))!=NULL) { - i=(int)(ptr-argv[arg]); - if (i>sNAMEMAX) { - i=sNAMEMAX; - error(200,argv[arg],sNAMEMAX); /* symbol too long, truncated to sNAMEMAX chars */ - } /* if */ - strlcpy(str,argv[arg],i+1); /* str holds symbol name */ - i=atoi(ptr+1); - add_constant(str,i,sGLOBAL,0); - } else { - strlcpy(str,argv[arg],sizeof(str)-5); /* -5 because default extension is ".sp" */ - set_extension(str,".sp",FALSE); - insert_sourcefile(str); - /* The output name is the first input name with a different extension, - * but it is stored in a different directory - */ - if (strlen(oname)==0) { - if ((ptr=strrchr(str,DIRSEP_CHAR))!=NULL) - ptr++; /* strip path */ - else - ptr=str; - assert(strlen(ptr)<_MAX_PATH); - strcpy(oname,ptr); - } /* if */ - set_extension(oname,".asm",TRUE); -#if !defined SC_LIGHT - if (sc_makereport && strlen(rname)==0) { - if ((ptr=strrchr(str,DIRSEP_CHAR))!=NULL) - ptr++; /* strip path */ - else - ptr=str; - assert(strlen(ptr)<_MAX_PATH); - strcpy(rname,ptr); - set_extension(rname,".xml",TRUE); - } /* if */ -#endif - } /* if */ - } /* for */ -} - -#if !defined SC_LIGHT -static void parserespf(char *filename,char *oname,char *ename,char *pname, - char *rname,char *codepage) -{ -#define MAX_OPTIONS 100 - FILE *fp; - char *string, *ptr, **argv; - int argc; - long size; - - if ((fp=fopen(filename,"r"))==NULL) - error(FATAL_ERROR_READ,filename); - /* load the complete file into memory */ - fseek(fp,0L,SEEK_END); - size=ftell(fp); - fseek(fp,0L,SEEK_SET); - assert(size [filename...] [options]\n\n"); - pc_printf("Options:\n"); - pc_printf(" -A alignment in bytes of the data segment and the stack\n"); - pc_printf(" -a output assembler code\n"); -#if 0 /* not toggleable in SourceMod */ - pc_printf(" -C[+/-] compact encoding for output file (default=%c)\n", sc_compress ? '+' : '-'); -#endif - pc_printf(" -c codepage name or number; e.g. 1252 for Windows Latin-1\n"); -#if defined dos_setdrive - pc_printf(" -Dpath active directory path\n"); -#endif -#if 0 /* not used for SourceMod */ - pc_printf(" -d debugging level (default=-d%d)\n",sc_debug); - pc_printf(" 0 no symbolic information, no run-time checks\n"); - pc_printf(" 1 run-time checks, no symbolic information\n"); - pc_printf(" 2 full debug information and dynamic checking\n"); - pc_printf(" 3 same as -d2, but implies -O0\n"); -#endif - pc_printf(" -e set name of error file (quiet compile)\n"); -#if defined __WIN32__ || defined _WIN32 || defined _Windows - pc_printf(" -H window handle to send a notification message on finish\n"); -#endif - pc_printf(" -h show included file paths\n"); - pc_printf(" -i path for include files\n"); - pc_printf(" -l create list file (preprocess only)\n"); - pc_printf(" -o set base name of (P-code) output file\n"); - pc_printf(" -O optimization level (default=-O%d)\n",pc_optimize); - pc_printf(" 0 no optimization\n"); -#if 0 /* not used for SourceMod */ - pc_printf(" 1 JIT-compatible optimizations only\n"); -#endif - pc_printf(" 2 full optimizations\n"); - pc_printf(" -p set name of \"prefix\" file\n"); -#if !defined SC_LIGHT - pc_printf(" -r write cross reference report to console or to specified file\n"); -#endif - pc_printf(" -S stack/heap size in cells (default=%d)\n",(int)pc_stksize); - pc_printf(" -s skip lines from the input file\n"); - pc_printf(" -t TAB indent size (in character positions, default=%d)\n",sc_tabsize); - pc_printf(" -v verbosity level; 0=quiet, 1=normal, 2=verbose (default=%d)\n",verbosity); - pc_printf(" -w disable a specific warning by its number\n"); - pc_printf(" -E treat warnings as errors\n"); - pc_printf(" -X abstract machine size limit in bytes\n"); - pc_printf(" -XD abstract machine data/stack size limit in bytes\n"); - pc_printf(" -\\ use '\\' for escape characters\n"); - pc_printf(" -^ use '^' for escape characters\n"); - pc_printf(" -;<+/-> require a semicolon to end each statement (default=%c)\n", sc_needsemicolon ? '+' : '-'); -#if 0 /* not allowed in SourceMod */ - pc_printf(" -([+/-] require parantheses for function invocation (default=%c)\n", optproccall ? '-' : '+'); -#endif - pc_printf(" sym=val define constant \"sym\" with value \"val\"\n"); - pc_printf(" sym= define constant \"sym\" with value 0\n"); -#if defined __WIN32__ || defined _WIN32 || defined _Windows || defined __MSDOS__ - pc_printf("\nOptions may start with a dash or a slash; the options \"-d0\" and \"/d0\" are\n"); - pc_printf("equivalent.\n"); -#endif - pc_printf("\nOptions with a value may optionally separate the value from the option letter\n"); - pc_printf("with a colon (\":\"), an equal sign (\"=\"), or a space (\" \"). That is, the options \"-d0\", \"-d=0\",\n"); - pc_printf("\"-d:0\", and \"-d 0\" are all equivalent. \"-;\" is an exception to this and cannot use a space.\n"); - } /* if */ - norun = 1; - longjmp(errbuf,3); /* user abort */ -} - -static void setconstants(void) -{ - int debug; - - assert(sc_status==statIDLE); - append_constval(&tagname_tab,"_",0,0);/* "untagged" */ - append_constval(&tagname_tab,"bool",1,0); - - pc_anytag = pc_addtag("any"); - pc_functag = pc_addtag_flags("Function", FIXEDTAG|FUNCTAG); - pc_tag_string = pc_addtag("String"); - sc_rationaltag = pc_addtag("Float"); - pc_tag_void = pc_addtag_flags("void", FIXEDTAG); - pc_tag_object = pc_addtag_flags("object", FIXEDTAG|OBJECTTAG); - pc_tag_bool = pc_addtag("bool"); - pc_tag_null_t = pc_addtag_flags("null_t", FIXEDTAG|OBJECTTAG); - pc_tag_nullfunc_t = pc_addtag_flags("nullfunc_t", FIXEDTAG|OBJECTTAG); - - add_constant("true",1,sGLOBAL,1); /* boolean flags */ - add_constant("false",0,sGLOBAL,1); - add_constant("EOS",0,sGLOBAL,0); /* End Of String, or '\0' */ - add_constant("INVALID_FUNCTION", -1, sGLOBAL, pc_tag_nullfunc_t); - add_constant("cellbits",32,sGLOBAL,0); -#if defined _I32_MAX - add_constant("cellmax",_I32_MAX,sGLOBAL,0); - add_constant("cellmin",_I32_MIN,sGLOBAL,0); -#else - add_constant("cellmax",LONG_MAX,sGLOBAL,0); - add_constant("cellmin",LONG_MIN,sGLOBAL,0); -#endif - add_constant("charbits",sCHARBITS,sGLOBAL,0); - add_constant("charmin",0,sGLOBAL,0); - add_constant("charmax",~(-1 << sCHARBITS) - 1,sGLOBAL,0); - add_constant("ucharmax",(1 << (sizeof(cell)-1)*8)-1,sGLOBAL,0); - - add_constant("__Pawn",VERSION_INT,sGLOBAL,0); - - debug=0; - if ((sc_debug & (sCHKBOUNDS | sSYMBOLIC))==(sCHKBOUNDS | sSYMBOLIC)) - debug=2; - else if ((sc_debug & sCHKBOUNDS)==sCHKBOUNDS) - debug=1; - add_constant("debug",debug,sGLOBAL,0); - - append_constval(&sc_automaton_tab,"",0,0); /* anonymous automaton */ -} - -static int getclassspec(int initialtok,int *fpublic,int *fstatic,int *fstock,int *fconst) -{ - int tok,err; - cell val; - char *str; - - assert(fconst!=NULL); - assert(fstock!=NULL); - assert(fstatic!=NULL); - assert(fpublic!=NULL); - *fconst=FALSE; - *fstock=FALSE; - *fstatic=FALSE; - *fpublic=FALSE; - switch (initialtok) { - case tCONST: - *fconst=TRUE; - break; - case tSTOCK: - *fstock=TRUE; - break; - case tSTATIC: - *fstatic=TRUE; - break; - case tPUBLIC: - *fpublic=TRUE; - break; - } /* switch */ - - err=0; - do { - tok=lex(&val,&str); /* read in (new) token */ - switch (tok) { - case tCONST: - if (*fconst) - err=42; /* invalid combination of class specifiers */ - *fconst=TRUE; - break; - case tSTOCK: - if (*fstock) - err=42; /* invalid combination of class specifiers */ - *fstock=TRUE; - break; - case tSTATIC: - if (*fstatic) - err=42; /* invalid combination of class specifiers */ - *fstatic=TRUE; - break; - case tPUBLIC: - if (*fpublic) - err=42; /* invalid combination of class specifiers */ - *fpublic=TRUE; - break; - default: - lexpush(); - tok=0; /* force break out of loop */ - } /* switch */ - } while (tok && err==0); - - /* extra checks */ - if (*fstatic && *fpublic) { - err=42; /* invalid combination of class specifiers */ - *fstatic=*fpublic=FALSE; - } /* if */ - - if (err) - error(err); - return err==0; -} - -static void dodecl(const token_t *tok) -{ - declinfo_t decl; - - if (tok->id == tNATIVE || tok->id == tFORWARD) { - parse_decl(&decl, DECLFLAG_MAYBE_FUNCTION); - funcstub(tok->id, &decl, NULL); - return; - } - - int fpublic = FALSE, fstock = FALSE, fstatic = FALSE, fconst = FALSE; - switch (tok->id) { - case tPUBLIC: - fpublic = TRUE; - break; - case tSTOCK: - fstock = TRUE; - if (matchtoken(tSTATIC)) - fstatic = TRUE; - break; - case tSTATIC: - fstatic = TRUE; - - // For compatibility, we must include this case. Though "stock" should - // come first. - if (matchtoken(tSTOCK)) - fstock = TRUE; - break; - } - - int flags = DECLFLAG_MAYBE_FUNCTION | DECLFLAG_VARIABLE | DECLFLAG_ENUMROOT; - if (tok->id == tNEW) - flags |= DECLFLAG_OLD; - - if (!parse_decl(&decl, flags)) { - // Error will have been reported earlier. Reset |decl| so we don't crash - // thinking tag -1 has every flag. - decl.type.tag = 0; - } - - // Hacky bag o' hints as to whether this is a variable decl. - bool probablyVariable = tok->id == tNEW || - decl.type.has_postdims || - !lexpeek('(') || - ((decl.type.usage & uCONST) == uCONST); - - if (!decl.opertok && probablyVariable) { - if (tok->id == tNEW && decl.type.is_new) - error(143); - if (decl.type.tag & STRUCTTAG) { - pstruct_t *pstruct = pstructs_find(pc_tagname(decl.type.tag)); - declstructvar(decl.name, fpublic, pstruct); - } else { - declglb(&decl, fpublic, fstatic, fstock); - } - } else { - if (!newfunc(&decl, NULL, fpublic, fstatic, fstock, NULL)) { - // Illegal function or declaration. Drop the line, reset literal queue. - error(10); - lexclr(TRUE); - litidx = 0; - } - } -} - -/* parse - process all input text - * - * At this level, only static declarations and function definitions are legal. - */ -static void parse(void) -{ - token_t tok; - - while (freading){ - switch (lextok(&tok)) { - case 0: - /* ignore zero's */ - break; - case tSYMBOL: -#if 0 - if (strcmp(tok.str, "class") == 0) { - domethodmap(Layout_Class); - break; - } -#endif - // Fallthrough. - case tINT: - case tOBJECT: - case tCHAR: - case tVOID: - case tLABEL: - lexpush(); - // Fallthrough. - case tNEW: - case tSTATIC: - case tPUBLIC: - case tSTOCK: - case tOPERATOR: - case tNATIVE: - case tFORWARD: - { - dodecl(&tok); - break; - } - case tFUNCTAG: - dofuncenum(FALSE); - break; - case tTYPEDEF: - dotypedef(); - break; - case tTYPESET: - dotypeset(); - break; - case tSTRUCT: - declstruct(); - break; - case tCONST: - decl_const(sGLOBAL); - break; - case tENUM: - decl_enum(sGLOBAL); - break; - case tFUNCENUM: - dofuncenum(TRUE); - break; - case tMETHODMAP: - domethodmap(Layout_MethodMap); - break; - case '}': - error(54); /* unmatched closing brace */ - break; - case '{': - error(55); /* start of function body without function header */ - break; - default: - if (freading) { - error(10); /* illegal function or declaration */ - lexclr(TRUE); /* drop the rest of the line */ - litidx=0; /* drop any literal arrays (strings) */ - } /* if */ - } /* switch */ - } /* while */ -} - -/* dumplits - * - * Dump the literal pool (strings etc.) - * - * Global references: litidx (referred to only) - */ -static void dumplits(void) -{ - int j,k; - - if (sc_status==statSKIP) - return; - - k=0; - while (k=litidx) - stgwrite("\n"); /* force a newline after 10 dumps */ - /* Note: stgwrite() buffers a line until it is complete. It recognizes - * the end of line as a sequence of "\n\0", so something like "\n\t" - * so should not be passed to stgwrite(). - */ - } /* while */ - } /* while */ -} - -/* dumpzero - * - * Dump zero's for default initial values - */ -static void dumpzero(int count) -{ - int i; - - if (sc_status==statSKIP || count<=0) - return; - assert(curseg==2); - defstorage(); - i=0; - while (count-- > 0) { - outval(0, FALSE); - i=(i+1) % 16; - stgwrite((i==0 || count==0) ? "\n" : " "); - if (i==0 && count>0) - defstorage(); - } /* while */ -} - -static void aligndata(int numbytes) -{ - assert(numbytes % sizeof(cell) == 0); /* alignment must be a multiple of - * the cell size */ - assert(numbytes!=0); - - if ((((glb_declared+litidx)*sizeof(cell)) % numbytes)!=0) { - while ((((glb_declared+litidx)*sizeof(cell)) % numbytes)!=0) - litadd(0); - } /* if */ - -} - -#if !defined SC_LIGHT -/* sc_attachdocumentation() - * appends documentation comments to the passed-in symbol, or to a global - * string if "sym" is NULL. - */ -void sc_attachdocumentation(symbol *sym) -{ - int line; - size_t length; - char *str,*doc; - - if (!sc_makereport || sc_status!=statFIRST || sc_parsenum>0) { - /* just clear the entire table */ - delete_docstringtable(); - return; - } /* if */ - /* in the case of state functions, multiple documentation sections may - * appear; we should concatenate these - * (with forward declarations, this is also already the case, so the assertion - * below is invalid) - */ - // assert(sym==NULL || sym->documentation==NULL || sym->states!=NULL); - - /* first check the size */ - length=0; - for (line=0; (str=get_docstring(line))!=NULL && *str!=sDOCSEP; line++) { - if (length>0) - length++; /* count 1 extra for a separating space */ - length+=strlen(str); - } /* for */ - if (sym==NULL && sc_documentation!=NULL) { - length += strlen(sc_documentation) + 1 + 4; /* plus 4 for "

" */ - assert(length>strlen(sc_documentation)); - } /* if */ - - if (length>0) { - /* allocate memory for the documentation */ - if (sym!=NULL && sym->documentation!=NULL) - length+=strlen(sym->documentation) + 1 + 4;/* plus 4 for "

" */ - doc=(char*)malloc((length+1)*sizeof(char)); - if (doc!=NULL) { - /* initialize string or concatenate */ - if (sym==NULL && sc_documentation!=NULL) { - strcpy(doc,sc_documentation); - strcat(doc,"

"); - } else if (sym!=NULL && sym->documentation!=NULL) { - strcpy(doc,sym->documentation); - strcat(doc,"

"); - free(sym->documentation); - sym->documentation=NULL; - } else { - doc[0]='\0'; - } /* if */ - /* collect all documentation */ - while ((str=get_docstring(0))!=NULL && *str!=sDOCSEP) { - if (doc[0]!='\0') - strcat(doc," "); - strcat(doc,str); - delete_docstring(0); - } /* while */ - if (str!=NULL) { - /* also delete the separator */ - assert(*str==sDOCSEP); - delete_docstring(0); - } /* if */ - if (sym!=NULL) { - assert(sym->documentation==NULL); - sym->documentation=doc; - } else { - if (sc_documentation!=NULL) - free(sc_documentation); - sc_documentation=doc; - } /* if */ - } /* if */ - } else { - /* delete an empty separator, if present */ - if ((str=get_docstring(0))!=NULL && *str==sDOCSEP) - delete_docstring(0); - } /* if */ -} - -static void insert_docstring_separator(void) -{ - char sep[2]={sDOCSEP,'\0'}; - insert_docstring(sep); -} -#else - #define sc_attachdocumentation(s) (void)(s) - #define insert_docstring_separator() -#endif - -/* declstruct - declare global struct symbols - * - * global references: glb_declared (altered) - */ -static void declstructvar(char *firstname,int fpublic, pstruct_t *pstruct) -{ - char name[sNAMEMAX+1]; - int tok,i; - cell val; - char *str; - int cur_litidx = 0; - cell *values, *found; - int usage; - symbol *mysym,*sym; - - strcpy(name, firstname); - - values = (cell *)malloc(pstruct->argcount * sizeof(cell)); - found = (cell *)malloc(pstruct->argcount * sizeof(cell)); - - memset(found, 0, sizeof(cell) * pstruct->argcount); - - //:TODO: Make this work with stock - - /** - * Lastly, very lastly, we will insert a copy of this variable. - * This is soley to expose the pubvar. - */ - usage = uREAD|uCONST|uSTRUCT; - if (fpublic) - usage |= uPUBLIC; - mysym = NULL; - for (sym=glbtab.next; sym!=NULL; sym=sym->next) { - if (strcmp(name, sym->name) == 0) { - if ((sym->usage & uSTRUCT) && sym->vclass == sGLOBAL) { - if (sym->usage & uDEFINE) { - error(21, name); - } else { - if (sym->usage & uPUBLIC && !fpublic) - error(42); - } - } else { - error(21, name); - } - mysym = sym; - break; - } - } - if (!mysym) - mysym=addsym(name, 0, iVARIABLE, sGLOBAL, pc_addtag(pstruct->name), usage); - - if (!matchtoken('=')) { - matchtoken(';'); - /* Mark it as undefined instead */ - mysym->usage = uSTOCK|uSTRUCT; - free(found); - free(values); - return; - } - - mysym->usage = usage; - needtoken('{'); - - do { - structarg_t *arg; - /* Detect early exit */ - if (matchtoken('}')) { - lexpush(); - break; - } - tok=lex(&val,&str); - if (tok != tSYMBOL) { - error(1, "-identifier-", str); - continue; - } - arg=pstructs_getarg(pstruct,str); - if (arg == NULL) - error(96, str, sym->name); - needtoken('='); - cur_litidx = litidx; - tok=lex(&val,&str); - if (!arg) { - continue; - } - if (tok == tSTRING) { - assert(litidx != 0); - if (arg->dimcount != 1) - { - error(48); - } else if (arg->tag != pc_tag_string) { - error(213); - } - values[arg->index] = glb_declared * sizeof(cell); - glb_declared += (litidx-cur_litidx); - found[arg->index] = 1; - } else if (tok == tNUMBER || tok == tRATIONAL) { - /* eat optional 'f' */ - matchtoken('f'); - if (arg->ident != iVARIABLE && arg->ident != iREFERENCE) { - error(23); - } else { - if ((arg->tag == pc_addtag("Float") && tok == tNUMBER) || - (arg->tag == 0 && tok == tRATIONAL)) - { - error(213); - } - if (arg->ident == iVARIABLE) { - values[arg->index] = val; - } else if (arg->ident == iREFERENCE) { - values[arg->index] = glb_declared * sizeof(cell); - glb_declared += 1; - litadd(val); - cur_litidx = litidx; - } - found[arg->index] = 1; - } - } else if (tok == tSYMBOL) { - for (sym=glbtab.next; sym!=NULL; sym=sym->next) { - if (sym->vclass != sGLOBAL) - continue; - if (strcmp(sym->name, str) == 0) { - if (arg->ident == iREFERENCE && sym->ident != iVARIABLE) { - error(97, str); - } else if (arg->ident == iARRAY) { - if (sym->ident != iARRAY) { - error(97, str); - } else { - /* :TODO: We should check dimension sizes here... */ - } - } else if (arg->ident == iREFARRAY) { - if (sym->ident != iARRAY) - error(97, str); - /* :TODO: Check dimension sizes! */ - } else { - error(97, str); - } - if (sym->tag != arg->tag) - error(213); - sym->usage |= uREAD; - values[arg->index] = sym->addr; - found[arg->index] = 1; - refer_symbol(sym, mysym); - break; - } - } - if (!sym) - error(17, str); - } else { - error(1, "-identifier-", str); - } - } while (matchtoken(',')); - needtoken('}'); - matchtoken(';'); /* eat up optional semicolon */ - - for (i=0; iargcount; i++) { - if (!found[i]) { - structarg_t *arg = pstruct->args[i]; - if (arg->ident == iREFARRAY) { - values[arg->index] = glb_declared * sizeof(cell); - glb_declared += 1; - litadd(0); - cur_litidx = litidx; - } else if (arg->ident == iVARIABLE) { - values[arg->index] = 0; - } else { - /* :TODO: broken for iARRAY! (unused tho) */ - } - } - } - - mysym->addr = glb_declared * sizeof(cell); - glb_declared += pstruct->argcount; - - for (i=0; iargcount; i++) - litadd(values[i]); - - begdseg(); - dumplits(); - litidx=0; - - free(found); - free(values); -} - -/* declglb - declare global symbols - * - * Declare a static (global) variable. Global variables are stored in - * the DATA segment. - * - * global references: glb_declared (altered) - */ -static void declglb(declinfo_t *decl,int fpublic,int fstatic,int fstock) -{ - int ispublic; - cell cidx; - ucell address; - int glb_incr; - int slength=0; - short filenum; - symbol *sym; -#if !defined NDEBUG - cell glbdecl=0; -#endif - declinfo_t orig_decl = *decl; - - assert(!fpublic || !fstatic); /* may not both be set */ - insert_docstring_separator(); /* see comment in newfunc() */ - filenum=fcurrent; /* save file number at the start of the declaration */ - - for (;;) { - typeinfo_t *type = &decl->type; - - check_void_decl(decl, TRUE); - - ispublic=fpublic; - if (decl->name[0]==PUBLIC_CHAR) { - ispublic=TRUE; /* implicitly public variable */ - assert(!fstatic); - } - slength = fix_char_size(decl); - assert(sc_curstates==0); - sc_curstates=getstates(decl->name); - if (sc_curstates<0) { - error(85,decl->name); /* empty state list on declaration */ - sc_curstates=0; - } else if (sc_curstates>0 && ispublic) { - error(88,decl->name); /* public variables may not have states */ - sc_curstates=0; - } /* if */ - sym=findconst(decl->name,NULL); - if (sym==NULL) { - sym=findglb(decl->name,sSTATEVAR); - /* if a global variable without states is found and this declaration has - * states, the declaration is okay - */ - if (sym!=NULL && sym->states==NULL && sc_curstates>0) - sym=NULL; /* set to NULL, we found the global variable */ - if (sc_curstates>0 && findglb(decl->name,sGLOBAL)!=NULL) - error(233,decl->name); /* state variable shadows a global variable */ - } /* if */ - /* we have either: - * a) not found a matching variable (or rejected it, because it was a shadow) - * b) found a global variable and we were looking for that global variable - * c) found a state variable in the automaton that we were looking for - */ - assert(sym==NULL - || (sym->states==NULL && sc_curstates==0) - || (sym->states!=NULL && sym->next!=NULL && sym->states->next->index==sc_curstates)); - /* a state variable may only have a single id in its list (so either this - * variable has no states, or it has a single list) - */ - assert(sym==NULL || sym->states==NULL || sym->states->next->next==NULL); - /* it is okay for the (global) variable to exist, as long as it belongs to - * a different automaton - */ - if (sym!=NULL && (sym->usage & uDEFINE)!=0) - error(21,decl->name); /* symbol already defined */ - /* if this variable is never used (which can be detected only in the - * second stage), shut off code generation - */ - cidx=0; /* only to avoid a compiler warning */ - if (sc_status==statWRITE && sym!=NULL && (sym->usage & (uREAD | uWRITTEN))==0) { - sc_status=statSKIP; - cidx=code_idx; - #if !defined NDEBUG - glbdecl=glb_declared; - #endif - } /* if */ - begdseg(); /* real (initialized) data in data segment */ - assert(litidx==0); /* literal queue should be empty */ - if (sc_alignnext) { - litidx=0; - aligndata(sc_dataalign); - dumplits(); /* dump the literal queue */ - sc_alignnext=FALSE; - litidx=0; /* global initial data is dumped, so restart at zero */ - } /* if */ - assert(litidx==0); /* literal queue should be empty (again) */ - if (type->ident == iREFARRAY) { - // Dynamc array in global scope. - assert(type->is_new); - error(162); - } - initials3(decl); - if (type->tag == pc_tag_string && type->numdim == 1 && !type->dim[type->numdim - 1]) { - slength = glbstringread; - } - assert(type->size>=litidx); - if (type->numdim == 1) - type->dim[0] = (int)type->size; - address=sizeof(cell)*glb_declared; - glb_incr=(int)type->size; - if (type->size != CELL_MAX && address==sizeof(cell)*glb_declared) { - dumplits(); /* dump the literal queue */ - dumpzero((int)(type->size)-litidx); - } /* if */ - litidx=0; - if (sym==NULL) { /* define only if not yet defined */ - sym=addvariable3(decl,address,sGLOBAL,slength); - } else { /* if declared but not yet defined, adjust the variable's address */ - assert((sym->states==NULL && sc_curstates==0) - || (sym->states->next!=NULL && sym->states->next->index==sc_curstates && sym->states->next->next==NULL)); - sym->addr=address; - sym->codeaddr=code_idx; - sym->usage|=uDEFINE; - } /* if */ - assert(sym!=NULL); - sc_curstates=0; - if (ispublic) - sym->usage|=uPUBLIC|uREAD; - if (decl->type.usage & uCONST) - sym->usage|=uCONST; - if (fstock) - sym->usage|=uSTOCK; - if (fstatic) - sym->fnumber=filenum; - sc_attachdocumentation(sym);/* attach any documenation to the variable */ - if (sc_status==statSKIP) { - sc_status=statWRITE; - code_idx=cidx; - assert(glb_declared==glbdecl); - } else { - glb_declared+=glb_incr; /* add total number of cells (if added to the end) */ - } /* if */ - - if (!matchtoken(',')) - break; - - if (decl->type.is_new) - reparse_new_decl(decl, DECLFLAG_VARIABLE|DECLFLAG_ENUMROOT); - else - reparse_old_decl(decl, DECLFLAG_VARIABLE|DECLFLAG_ENUMROOT); - }; - needtoken(tTERM); /* if not comma, must be semicolumn */ -} - -static bool parse_local_array_initializer(typeinfo_t *type, int *curlit, int *slength) -{ - if (sc_alignnext) { - aligndata(sc_dataalign); - sc_alignnext=FALSE; - } /* if */ - *curlit = litidx; /* save current index in the literal table */ - if (type->numdim && !type->dim[type->numdim-1]) - type->size = 0; - initials(type->ident,type->tag,&type->size,type->dim,type->numdim,type->enumroot); - if (type->tag == pc_tag_string && type->numdim == 1 && !type->dim[type->numdim - 1]) - *slength = glbstringread; - if (type->size == 0) - return false; - if (type->numdim == 1) - type->dim[0] = type->size; - return true; -} - -/* declloc - declare local symbols - * - * Declare local (automatic) variables. Since these variables are relative - * to the STACK, there is no switch to the DATA segment. These variables - * cannot be initialized either. - * - * global references: declared (altered) - * funcstatus (referred to only) - */ -static void declloc(int tokid) -{ - symbol *sym; - value lval = {0}; - int cur_lit=0; - int staging_start; - int slength = 0; - int fstatic = (tokid == tSTATIC); - declinfo_t decl; - - int declflags = DECLFLAG_VARIABLE | DECLFLAG_ENUMROOT | DECLFLAG_DYNAMIC_ARRAYS; - if (tokid == tNEW || tokid == tDECL) - declflags |= DECLFLAG_OLD; - else if (tokid == tNEWDECL) - declflags |= DECLFLAG_NEW; - - parse_decl(&decl, declflags); - - for (;;) { - typeinfo_t *type = &decl.type; - - slength=0; - - if (decl.name[0]==PUBLIC_CHAR) - error(56, decl.name); /* local variables cannot be public */ - - /* Note: block locals may be named identical to locals at higher - * compound blocks (as with standard C); so we must check (and add) - * the "nesting level" of local variables to verify the - * multi-definition of symbols. - */ - if ((sym=findloc(decl.name))!=NULL && sym->compound==nestlevel) - error(21, decl.name); /* symbol already defined */ - - /* Although valid, a local variable whose name is equal to that - * of a global variable or to that of a local variable at a lower - * level might indicate a bug. - */ - if (((sym=findloc(decl.name)) != NULL && sym->compound != nestlevel) || - findglb(decl.name,sGLOBAL) != NULL) - { - error(219, decl.name); /* variable shadows another symbol */ - } - - slength = fix_char_size(&decl); - - if (fstatic && type->ident == iREFARRAY) - error(165); - - if (type->ident == iARRAY || fstatic) { - if (!parse_local_array_initializer(type, &cur_lit, &slength)) - return; - } - /* reserve memory (on the stack) for the variable */ - if (fstatic) { - /* write zeros for uninitialized fields */ - while (litidx < cur_lit + type->size) - litadd(0); - sym=addvariable2(decl.name,(cur_lit+glb_declared)*sizeof(cell),type->ident,sSTATIC, - type->tag,type->dim,type->numdim,type->idxtag,slength); - } else if (type->ident!=iREFARRAY) { - declared+=type->size; /* variables are put on stack, adjust "declared" */ - sym=addvariable2(decl.name,-declared*sizeof(cell),type->ident,sLOCAL,type->tag, - type->dim,type->numdim,type->idxtag,slength); - if (type->ident == iVARIABLE) { - assert(!staging); - stgset(TRUE); /* start stage-buffering */ - assert(stgidx==0); - staging_start=stgidx; - } /* if */ - markexpr(sLDECL,decl.name,-declared*sizeof(cell)); /* mark for better optimization */ - modstk(-type->size * sizeof(cell)); - markstack(MEMUSE_STATIC, type->size); - assert(curfunc!=NULL); - assert((curfunc->usage & uNATIVE)==0); - if (curfunc->x.stacksizex.stacksize=declared+1; /* +1 for PROC opcode */ - } else if (type->ident == iREFARRAY) { - // Generate the symbol so we can access its stack address during initialization. - declared+=1; /* one cell for address */ - sym=addvariable(decl.name,-declared*sizeof(cell),type->ident,sLOCAL,type->tag,type->dim,type->numdim,type->idxtag); - - // If we're new-style, a REFARRAY indicates prefix brackets. We need to - // be initialized since we don't support fully dynamic arrays yet; i.e., - // "int[] x;" doesn't have any sensible semantics. There are two - // acceptable initialization sequences: "new " and a string - // literal. In other cases (such as a fixed-array literal), we error. - // - // For now, we only implement the string literal initializer. - if (type->is_new && needtoken('=')) { - if (type->isCharArray() && !lexpeek(tNEW)) { - // Error if we're assigning something other than a string literal. - needtoken(tSTRING); - - // Note: the genarray call pushes the result array into the stack - // slot of our local variable - we can access |sym| after. - // - // push.c N - // genarray 1 - // const.pri DAT + offset - // load.s.alt sym->addr - // movs N * sizeof(cell) - int cells = litidx - cur_lit; - pushval(cells); - genarray(1, false); - ldconst((cur_lit + glb_declared) * sizeof(cell), sPRI); - copyarray(sym, cells * sizeof(cell)); - } else if (matchtoken(tNEW)) { - int tag = 0; - if (parse_new_typename(NULL, &tag)) { - if (tag != type->tag) - error(164, pc_typename(tag), pc_typename(type->tag)); - } - - for (int i = 0; i < type->numdim; i++) { - if (!needtoken('[')) - break; - - value val; - symbol *child; - int ident = doexpr2( - TRUE, FALSE, TRUE, FALSE, - &type->idxtag[i], - &child, 0, &val); - if (i == type->numdim - 1 && type->tag == pc_tag_string) - stradjust(sPRI); - pushreg(sPRI); - - switch (ident) { - case iVARIABLE: - case iEXPRESSION: - case iARRAYCELL: - case iCONSTEXPR: - break; - default: - error(29); - break; - } - - if (!needtoken(']')) - break; - } - - genarray(type->numdim, true); - } else if (lexpeek('{')) { - // Dynamic array with fixed initializer. - error(160); - - // Parse just to clear the tokens. First give '=' back. - lexpush(); - if (!parse_local_array_initializer(type, &cur_lit, &slength)) - return; - } else { - // Give the '=' back so we error later. - lexpush(); - } - } - - /* genarray() pushes the address onto the stack, so we don't need to call modstk() here! */ - markheap(MEMUSE_DYNAMIC, 0); - markstack(MEMUSE_STATIC, 1); - assert(curfunc != NULL && ((curfunc->usage & uNATIVE) == 0)); - if (curfunc->x.stacksizex.stacksize=declared+1; /* +1 for PROC opcode */ - } /* if */ - /* now that we have reserved memory for the variable, we can proceed - * to initialize it */ - assert(sym!=NULL); /* we declared it, it must be there */ - sym->compound=nestlevel; /* for multiple declaration/shadowing check */ - if (type->usage & uCONST) - sym->usage|=uCONST; - if (!fstatic) { /* static variables already initialized */ - if (type->ident == iVARIABLE) { - /* simple variable, also supports initialization */ - int ctag = type->tag; /* set to "tag" by default */ - int explicit_init=FALSE;/* is the variable explicitly initialized? */ - int cident = type->ident; - if (matchtoken('=')) { - if (!autozero) - error(10); - cident=doexpr(FALSE,FALSE,FALSE,FALSE,&ctag,NULL,TRUE); - explicit_init=TRUE; - } else { - if (autozero) - ldconst(0,sPRI); /* uninitialized variable, set to zero */ - } /* if */ - if (autozero) { - /* now try to save the value (still in PRI) in the variable */ - lval.sym=sym; - lval.ident=iVARIABLE; - lval.constval=0; - lval.tag=type->tag; - check_userop(NULL,ctag,lval.tag,2,NULL,&ctag); - store(&lval); - markexpr(sEXPR,NULL,0); /* full expression ends after the store */ - } - assert(staging); /* end staging phase (optimize expression) */ - stgout(staging_start); - stgset(FALSE); - if (!matchtag_string(cident, ctag)) - matchtag(type->tag,ctag,TRUE); - /* if the variable was not explicitly initialized, reset the - * "uWRITTEN" flag that store() set */ - if (!explicit_init) - sym->usage &= ~uWRITTEN; - } else if (type->ident != iREFARRAY) { - /* an array */ - assert(cur_lit>=0 && cur_lit<=litidx && litidx<=litmax); - assert(type->size > 0 && type->size >= sym->dim.array.length); - assert(type->numdim > 1 || type->size == sym->dim.array.length); - if (autozero) { - /* final literal values that are zero make no sense to put in the literal - * pool, because values get zero-initialized anyway; we check for this, - * because users often explicitly initialize strings to "" - */ - while (litidx>cur_lit && litq[litidx-1]==0) - litidx--; - /* if the array is not completely filled, set all values to zero first */ - if (litidx - cur_lit < type->size && (ucell)type->size < CELL_MAX) - fillarray(sym, type->size * sizeof(cell), 0); - } - if (cur_lit=0 && cur<=numdim); - if (cur==numdim) - return 0; - subsize=calc_arraysize(dim,numdim,cur+1); - newsize=dim[cur]+dim[cur]*subsize; - if ((ucell)subsize>=CELL_MAX || newsize>=CELL_MAX || newsize*sizeof(cell)>=CELL_MAX) - return CELL_MAX; - return newsize; -} - -static cell gen_indirection_vecs(array_info_t *ar, int dim, cell cur_offs) -{ - int i; - cell write_offs = cur_offs; - cell *data_offs = ar->data_offs; - - cur_offs += ar->dim_list[dim]; - - /** - * Dimension n-x where x > 2 will have sub-vectors. - * Otherwise, we just need to reference the data section. - */ - if (ar->dim_count > 2 && dim < ar->dim_count - 2) - { - /** - * For each index at this dimension, write offstes to our sub-vectors. - * After we write one sub-vector, we generate its sub-vectors recursively. - * At the end, we're given the next offset we can use. - */ - for (i = 0; i < ar->dim_list[dim]; i++) - { - ar->base[write_offs] = (cur_offs - write_offs) * sizeof(cell); - write_offs++; - ar->cur_dims[dim] = i; - cur_offs = gen_indirection_vecs(ar, dim + 1, cur_offs); - } - } else if (ar->dim_count > 1) { - /** - * In this section, there are no sub-vectors, we need to write offsets - * to the data. This is separate so the data stays in one big chunk. - * The data offset will increment by the size of the last dimension, - * because that is where the data is finally computed as. But the last - * dimension can be of variable size, so we have to detect that. - */ - if (ar->dim_list[dim + 1] == 0) - { - int vec_start = 0; - - /** - * Using the precalculated offsets, compute an index into the last - * dimension array. - */ - for (i = 0; i < dim; i++) - { - vec_start += ar->cur_dims[i] * ar->dim_offs_precalc[i]; - } - - /** - * Now, vec_start points to a vector of last dimension offsets for - * the preceding dimension combination(s). - * I.e. (1,2,i,j) in [3][4][5][] will be: - * j = 1*(4*5) + 2*(5) + i, and the parenthetical expressions are - * precalculated for us so we can easily generalize here. - */ - for (i = 0; i < ar->dim_list[dim]; i++) - { - ar->base[write_offs] = (*data_offs - write_offs) * sizeof(cell); - write_offs++; - *data_offs = *data_offs + ar->lastdim_list[vec_start + i]; - } - } else { - /** - * The last dimension size is constant. There's no extra work to - * compute the last dimension size. - */ - for (i = 0; i < ar->dim_list[dim]; i++) - { - ar->base[write_offs] = (*data_offs - write_offs) * sizeof(cell); - write_offs++; - *data_offs = *data_offs + ar->dim_list[dim + 1]; - } - } - } - - return cur_offs; -} - -static cell calc_indirection(const int dim_list[], int dim_count, int dim) -{ - cell size = dim_list[dim]; - - if (dim < dim_count - 2) - { - size += dim_list[dim] * calc_indirection(dim_list, dim_count, dim + 1); - } - - return size; -} - -static void adjust_indirectiontables(int dim[],int numdim,int cur,cell increment, - int startlit,constvalue *lastdim,int *skipdim) -{ - /* Find how many cells the indirection table will be */ - cell tbl_size; - int *dyn_list = NULL; - int cur_dims[sDIMEN_MAX]; - cell dim_offset_precalc[sDIMEN_MAX]; - array_info_t ar; - - if (numdim == 1) - { - return; - } - - tbl_size = calc_indirection(dim, numdim, 0); - memset(cur_dims, 0, sizeof(cur_dims)); - - /** - * Flatten the last dimension array list -- this makes - * things MUCH easier in the indirection calculator. - */ - if (lastdim) - { - int i; - constvalue *ld = lastdim->next; - - /* Get the total number of last dimensions. */ - for (i = 0; ld != NULL; i++, ld = ld->next) - { - /* Nothing */ - } - /* Store them in an array instead of a linked list. */ - dyn_list = (int *)malloc(sizeof(int) * i); - for (i = 0, ld = lastdim->next; - ld != NULL; - i++, ld = ld->next) - { - dyn_list[i] = ld->value; - } - - /** - * Pre-calculate all of the offsets. This speeds up and simplifies - * the indirection process. For example, if we have an array like: - * [a][b][c][d][], and given (A,B,C), we want to find the size of - * the last dimension [A][B][C][i], we must do: - * - * list[A*(b*c*d) + B*(c*d) + C*(d) + i] - * - * Generalizing this algorithm in the indirection process is expensive, - * so we lessen the need for nested loops by pre-computing the parts: - * (b*c*d), (c*d), and (d). - * - * In other words, finding the offset to dimension N at index I is - * I * (S[N+1] * S[N+2] ... S[N+n-1]) where S[] is the size of dimension - * function, and n is the index of the last dimension. - */ - for (i = 0; i < numdim - 1; i++) - { - int j; - - dim_offset_precalc[i] = 1; - for (j = i + 1; j < numdim - 1; j++) - { - dim_offset_precalc[i] *= dim[j]; - } - } - - ar.dim_offs_precalc = dim_offset_precalc; - ar.lastdim_list = dyn_list; - } else { - ar.dim_offs_precalc = NULL; - ar.lastdim_list = NULL; - } - - ar.base = &litq[startlit]; - ar.data_offs = &tbl_size; - ar.dim_list = dim; - ar.dim_count = numdim; - ar.cur_dims = cur_dims; - - gen_indirection_vecs(&ar, 0, 0); - - free(dyn_list); -} - -/* initials - * - * Initialize global objects and local arrays. - * size==array cells (count), if 0 on input, the routine counts the number of elements - * tag==required tagname id (not the returned tag) - * - * Global references: litidx (altered) - */ -static void initials2(int ident,int tag,cell *size,int dim[],int numdim, - constvalue *enumroot, int eq_match_override, int curlit_override) -{ - int ctag; - cell tablesize; - int curlit=(curlit_override == -1) ? litidx : curlit_override; - int err=0; - - if (eq_match_override == -1) { - eq_match_override = matchtoken('='); - } - - if (numdim > 2) { - int d, hasEmpty = 0; - for (d = 0; d < numdim; d++) { - if (dim[d] == 0) - hasEmpty++; - } - /* Work around ambug 4977 where indirection vectors are computed wrong. */ - if (hasEmpty && hasEmpty < numdim-1 && dim[numdim-1]) { - error(101); - /* This will assert with something like [2][][256] from a separate bug. - * To prevent this assert, automatically wipe the rest of the dims. - */ - for (d = 0; d < numdim - 1; d++) - dim[d] = 0; - } - } - - if (!eq_match_override) { - assert(ident!=iARRAY || numdim>0); - if (ident==iARRAY && dim[numdim-1]==0) { - /* declared as "myvar[];" which is senseless (note: this *does* make - * sense in the case of a iREFARRAY, which is a function parameter) - */ - error(9); /* array has zero length -> invalid size */ - } /* if */ - if (ident==iARRAY) { - assert(numdim>0 && numdim<=sDIMEN_MAX); - *size=calc_arraysize(dim,numdim,0); - if (*size==(cell)CELL_MAX) { - error(9); /* array is too big -> invalid size */ - return; - } /* if */ - /* first reserve space for the indirection vectors of the array, then - * adjust it to contain the proper values - * (do not use dumpzero(), as it bypasses the literal queue) - */ - for (tablesize=calc_arraysize(dim,numdim-1,0); tablesize>0; tablesize--) - litadd(0); - if (dim[numdim-1]!=0) /* error 9 has already been given */ - adjust_indirectiontables(dim,numdim,0,0,curlit,NULL,NULL); - } /* if */ - return; - } /* if */ - - if (ident==iVARIABLE) { - assert(*size==1); - init(ident,&ctag,NULL); - matchtag(tag,ctag,TRUE); - } else { - assert(numdim>0); - if (numdim==1) { - *size=initvector(ident,tag,dim[0],FALSE,enumroot,NULL); - } else { - int errorfound=FALSE; - int counteddim[sDIMEN_MAX]; - int idx; - constvalue lastdim={NULL,"",0,0}; /* sizes of the final dimension */ - int skipdim=0; - - if (dim[numdim-1]!=0) - *size=calc_arraysize(dim,numdim,0); /* calc. full size, if known */ - /* already reserve space for the indirection tables (for an array with - * known dimensions) - * (do not use dumpzero(), as it bypasses the literal queue) - */ - for (tablesize=calc_arraysize(dim,numdim-1,0); tablesize>0; tablesize--) - litadd(0); - /* now initialize the sub-arrays */ - memset(counteddim,0,sizeof counteddim); - initarray(ident,tag,dim,numdim,0,curlit,counteddim,&lastdim,enumroot,&errorfound); - /* check the specified array dimensions with the initializer counts */ - for (idx=0; idxdim[idx]) { - error(18); /* initialization data exceeds declared size */ - err++; - } /* if */ - } /* for */ - if (numdim>1 && dim[numdim-1]==0) { - /* also look whether, by any chance, all "counted" final dimensions are - * the same value; if so, we can store this - */ - constvalue *ld=lastdim.next; - int d,match; - for (d=0; dname,NULL,16)==d); - if (d==0) - match=ld->value; - else if (match!=ld->value) - break; - ld=ld->next; - } /* for */ - if (d==dim[numdim-2]) - dim[numdim-1]=match; - } /* if */ - /* after all arrays have been initalized, we know the (major) dimensions - * of the array and we can properly adjust the indirection vectors - */ - if (err==0) - adjust_indirectiontables(dim,numdim,0,0,curlit,&lastdim,&skipdim); - delete_consttable(&lastdim); /* clear list of minor dimension sizes */ - } /* if */ - } /* if */ - - if (*size==0) - *size=litidx-curlit; /* number of elements defined */ -} - -static void initials(int ident,int tag,cell *size,int dim[],int numdim, - constvalue *enumroot) -{ - initials2(ident, tag, size, dim, numdim, enumroot, -1, -1); -} - -static void initials3(declinfo_t *decl) -{ - typeinfo_t *type = &decl->type; - initials(type->ident, type->tag, &type->size, type->dim, type->numdim, type->enumroot); -} - -static cell initarray(int ident,int tag,int dim[],int numdim,int cur, - int startlit,int counteddim[],constvalue *lastdim, - constvalue *enumroot,int *errorfound) -{ - cell dsize,totalsize; - int idx,abortparse; - - assert(cur>=0 && cur=0); - assert(cur+2<=numdim);/* there must be 2 dimensions or more to do */ - assert(errorfound!=NULL && *errorfound==FALSE); - totalsize=0; - needtoken('{'); - for (idx=0,abortparse=FALSE; !abortparse; idx++) { - - /* In case the major dimension is zero, we need to store the offset - * to the newly detected sub-array into the indirection table; i.e. - * this table needs to be expanded and updated. - * In the current design, the indirection vectors for a multi-dimensional - * array are adjusted after parsing all initializers. Hence, it is only - * necessary at this point to reserve space for an extra cell in the - * indirection vector. - */ - if (dim[cur]==0) { - litinsert(0,startlit); - } else if (idx>=dim[cur]) { - error(18); /* initialization data exceeds array size */ - break; - } /* if */ - if (cur+20) { - if (idxcounteddim[cur]) - error(18); /* initialization data exceeds declared size */ - } /* if */ - counteddim[cur]=idx; - - return totalsize+dim[cur]; /* size of sub-arrays + indirection vector */ -} - -/* initvector - * Initialize a single dimensional array - */ -static cell initvector(int ident,int tag,cell size,int fillzero, - constvalue *enumroot,int *errorfound) -{ - cell prev1=0,prev2=0; - int ellips=FALSE; - int curlit=litidx; - int rtag,ctag; - - assert(ident==iARRAY || ident==iREFARRAY); - if (matchtoken('{')) { - constvalue *enumfield=(enumroot!=NULL) ? enumroot->next : NULL; - do { - int fieldlit=litidx; - int matchbrace,i; - if (matchtoken('}')) { /* to allow for trailing ',' after the initialization */ - lexpush(); - break; - } /* if */ - if ((ellips=matchtoken(tELLIPS))!=0) - break; - /* for enumeration fields, allow another level of braces ("{...}") */ - matchbrace=0; /* preset */ - ellips=0; - if (enumfield!=NULL) - matchbrace=matchtoken('{'); - for ( ;; ) { - prev2=prev1; - prev1=init(ident,&ctag,errorfound); - if (!matchbrace) - break; - if ((ellips=matchtoken(tELLIPS))!=0) - break; - if (!matchtoken(',')) { - needtoken('}'); - break; - } /* for */ - } /* for */ - /* if this array is based on an enumeration, fill the "field" up with - * zeros, and toggle the tag - */ - if (enumroot!=NULL && enumfield==NULL) - error(227); /* more initializers than enum fields */ - rtag=tag; /* preset, may be overridden by enum field tag */ - if (enumfield!=NULL) { - cell step; - int cmptag=enumfield->index; - symbol *symfield=findconst(enumfield->name,&cmptag); - if (cmptag>1) - error(91,enumfield->name); /* ambiguous constant, needs tag override */ - assert(symfield!=NULL); - assert(fieldlitsymfield->dim.array.length) - error(228); /* length of initializer exceeds size of the enum field */ - if (ellips) { - step=prev1-prev2; - } else { - step=0; - prev1=0; - } /* if */ - for (i=litidx-fieldlit; idim.array.length; i++) { - prev1+=step; - litadd(prev1); - } /* for */ - rtag=symfield->x.tags.index; /* set the expected tag to the index tag */ - enumfield=enumfield->next; - } /* if */ - matchtag(rtag,ctag,TRUE); - } while (matchtoken(',')); /* do */ - needtoken('}'); - } else { - if (!lexpeek('}')) - { - init(ident,&ctag,errorfound); - matchtag(tag,ctag,TRUE); - } - } /* if */ - /* fill up the literal queue with a series */ - if (ellips) { - cell step=((litidx-curlit)==1) ? (cell)0 : prev1-prev2; - if (size==0 || (litidx-curlit)==0) - error(41); /* invalid ellipsis, array size unknown */ - else if ((litidx-curlit)==(int)size) - error(18); /* initialization data exceeds declared size */ - while ((litidx-curlit)<(int)size) { - prev1+=step; - litadd(prev1); - } /* while */ - } /* if */ - if (fillzero && size>0) { - while ((litidx-curlit)<(int)size) - litadd(0); - } /* if */ - if (size==0) { - size=litidx-curlit; /* number of elements defined */ - } else if (litidx-curlit>(int)size) { /* e.g. "myvar[3]={1,2,3,4};" */ - error(18); /* initialization data exceeds declared size */ - litidx=(int)size+curlit; /* avoid overflow in memory moves */ - } /* if */ - return size; -} - -/* init - * - * Evaluate one initializer. - */ -static cell init(int ident,int *tag,int *errorfound) -{ - cell i = 0; - - if (matchtoken(tSTRING)){ - /* lex() automatically stores strings in the literal table (and - * increases "litidx") */ - if (ident==iVARIABLE) { - error(6); /* must be assigned to an array */ - litidx=1; /* reset literal queue */ - } /* if */ - *tag=pc_tag_string; - } else if (exprconst(&i,tag,NULL)){ - litadd(i); /* store expression result in literal table */ - } else { - if (errorfound!=NULL) - *errorfound=TRUE; - } /* if */ - return i; -} - -/* needsub - * - * Get required array size - */ -static cell needsub(int *tag,constvalue **enumroot) -{ - cell val; - symbol *sym; - - assert(tag!=NULL); - *tag=0; - if (enumroot!=NULL) - *enumroot=NULL; /* preset */ - if (matchtoken(']')) /* we have already seen "[" */ - return 0; /* zero size (like "char msg[]") */ - - exprconst(&val,tag,&sym); /* get value (must be constant expression) */ - if (val<0) { - error(9); /* negative array size is invalid; assumed zero */ - val=0; - } /* if */ - needtoken(']'); - - if (enumroot!=NULL) { - /* get the field list for an enumeration */ - assert(*enumroot==NULL);/* should have been preset */ - assert(sym==NULL || sym->ident==iCONSTEXPR); - if (sym!=NULL && (sym->usage & uENUMROOT)==uENUMROOT) { - assert(sym->dim.enumlist!=NULL); - *enumroot=sym->dim.enumlist; - } /* if */ - } /* if */ - - return val; /* return array size */ -} - -/* decl_const - declare a single constant - * - */ -static void decl_const(int vclass) -{ - char constname[sNAMEMAX+1]; - cell val; - token_t tok; - int exprtag; - int symbolline; - symbol *sym; - - insert_docstring_separator(); /* see comment in newfunc() */ - do { - int orgfline; - - // Since spcomp is terrible, it's hard to use parse_decl() here - there - // are all sorts of restrictions on const. We just implement some quick - // detection instead. - int tag = 0; - switch (lextok(&tok)) { - case tINT: - case tOBJECT: - case tCHAR: - tag = parse_new_typename(&tok); - break; - case tLABEL: - tag = pc_addtag(tok.str); - break; - case tSYMBOL: - // See if we can peek ahead another symbol. - if (lexpeek(tSYMBOL)) { - // This is a new-style declaration. - tag = parse_new_typename(&tok); - } else { - // Otherwise, we got "const X ..." so the tag is int. Give the - // symbol back to the lexer so we get it as the name. - lexpush(); - } - break; - default: - error(122); - break; - } - - if (expecttoken(tSYMBOL, &tok)) - strcpy(constname, tok.str); - else - strcpy(constname, "__unknown__"); - - symbolline=fline; /* save line where symbol was found */ - needtoken('='); - exprconst(&val,&exprtag,NULL); /* get value */ - - /* add_constant() checks for duplicate definitions */ - /* temporarily reset the line number to where the symbol was defined */ - orgfline=fline; - fline=symbolline; - matchtag(tag,exprtag,FALSE); - fline=orgfline; - - sym=add_constant(constname,val,vclass,tag); - if (sym!=NULL) - sc_attachdocumentation(sym);/* attach any documenation to the constant */ - } while (matchtoken(',')); /* enddo */ /* more? */ - needtoken(tTERM); -} - -static void check_struct_name(const char *name) -{ - LayoutSpec spec = deduce_layout_spec_by_name(name); - if (!can_redef_layout_spec(spec, Layout_PawnStruct)) - error(110, name, layout_spec_name(spec)); - if (!isupper(*name)) - error(109, "struct"); -} - -/* - * declstruct - declare a struct type - */ -static void declstruct(void) -{ - cell val; - char *str; - int tok; - pstruct_t *pstruct; - - /* get the explicit tag (required!) */ - tok = lex(&val,&str); - if (tok != tSYMBOL) { - error(93); - } else { - check_struct_name(str); - } - - pstruct = pstructs_add(str); - - pc_addtag_flags(pstruct->name, STRUCTTAG|FIXEDTAG); - - needtoken('{'); - do { - if (matchtoken('}')) { - /* Quick exit */ - lexpush(); - break; - } - - declinfo_t decl; - memset(&decl, 0, sizeof(decl)); - - decl.type.ident = iVARIABLE; - decl.type.size = 1; - if (!needtoken(tPUBLIC) || !parse_new_decl(&decl, NULL, DECLFLAG_FIELD)) { - // skip the rest of the line. - lexclr(TRUE); - break; - } - - structarg_t arg; - memset(&arg, 0, sizeof(arg)); - - arg.tag = decl.type.tag; - arg.dimcount = decl.type.numdim; - memcpy(arg.dims, decl.type.dim, sizeof(int) * arg.dimcount); - strcpy(arg.name, decl.name); - arg.fconst = !!(decl.type.usage & uCONST); - arg.ident = decl.type.ident; - if (arg.ident == iARRAY) - arg.ident = iREFARRAY; - - if (pstructs_addarg(pstruct, &arg) == NULL) - error(103, arg.name, layout_spec_name(Layout_PawnStruct)); - - require_newline(TRUE); - } while (!lexpeek('}')); - needtoken('}'); - matchtoken(';'); /* eat up optional semicolon */ -} - -// Consumes a line, returns FALSE if EOF hit. -static int consume_line() -{ - int val; - char *str; - - // First check for EOF. - if (lex(&val, &str) == 0) - return FALSE; - lexpush(); - - while (!matchtoken(tTERM)) { - // Check for EOF. - if (lex(&val, &str) == 0) - return FALSE; - } - - return TRUE; -} - -static int parse_new_typename(const token_t *tok) -{ - token_t tmp; - - if (!tok) { - lextok(&tmp); - tok = &tmp; - } - - switch (tok->id) { - case tINT: - return 0; - case tCHAR: - return pc_tag_string; - case tVOID: - return pc_tag_void; - case tOBJECT: - return pc_tag_object; - case tLABEL: - error(120); - return pc_addtag(tok->str); - case tSYMBOL: - { - if (strcmp(tok->str, "float") == 0) - return sc_rationaltag; - if (strcmp(tok->str, "bool") == 0) - return pc_tag_bool; - int tag = pc_findtag(tok->str); - if (tag == sc_rationaltag) { - error(98, "Float", "float"); - } else if (tag == pc_tag_string) { - error(98, "String", "char"); - } else if (tag == 0) { - error(98, "_", "int"); - } else if (tag == -1) { - error(139, tok->str); - tag = 0; - } else if (tag != pc_anytag) { - // Perform some basic filters so we can start narrowing down what can - // be used as a type. - if (!(tag & TAGTYPEMASK)) - error(139, tok->str); - } - return tag; - } - } - - error(122); - return -1; -} - -bool parse_new_typename(const token_t *tok, int *tagp) -{ - int tag = parse_new_typename(tok); - if (tag >= 0) - *tagp = tag; - else - *tagp = 0; - return true; -} - -static int parse_new_typeexpr(typeinfo_t *type, const token_t *first, int flags) -{ - token_t tok; - - if (first) - tok = *first; - else - lextok(&tok); - - if (tok.id == tCONST) { - if (type->usage & uCONST) - error(138); - type->usage |= uCONST; - lextok(&tok); - } - - if (!parse_new_typename(&tok, &type->tag)) - goto err_out; - - // Note: we could have already filled in the prefix array bits, so we check - // that ident != iARRAY before looking for an open bracket. - if (type->ident != iARRAY && matchtoken('[')) { - do { - if (type->numdim == sDIMEN_MAX) { - error(53); - break; - } - type->dim[type->numdim++] = 0; - if (!matchtoken(']')) { - error(140); - goto err_out; - } - } while (matchtoken('[')); - type->ident = iREFARRAY; - type->size = 0; - } - - if (flags & DECLFLAG_ARGUMENT) { - if (matchtoken('&')) { - if (type->ident == iARRAY) { - error(137); - goto err_out; - } - type->ident = iREFERENCE; - } - } - - type->tags[0] = type->tag; - type->numtags = 1; - return TRUE; - -err_out: - type->tags[0] = type->tag; - type->numtags = 1; - return FALSE; -} - -static void parse_old_array_dims(declinfo_t *decl, int flags) -{ - typeinfo_t *type = &decl->type; - constvalue **enumrootp; - - // Illegal declaration (we'll have a name since ref requires decl). - if (type->ident == iREFERENCE) - error(67, decl->name); - - if (flags & DECLFLAG_ENUMROOT) - enumrootp = &type->enumroot; - else - enumrootp = NULL; - - if (flags & DECLFLAG_DYNAMIC_ARRAYS) { - // This is a huge hack for declloc() - we'll generate the array code right - // into the staging buffer if needed. - cell staging_ptr; - int staging_index; - - int was_staging = staging; - if (!was_staging) - stgset(TRUE); - stgget(&staging_index, &staging_ptr); - - type->size = 0; - - do { - if (type->numdim == sDIMEN_MAX) { - error(53); - return; - } - - if (type->numdim > 0) { - // Push the last dimension size, which is in PRI. - pushreg(sPRI); - } - - if (matchtoken(']')) { - ldconst(0, sPRI); - type->idxtag[type->numdim] = 0; - type->dim[type->numdim] = 0; - type->numdim++; - continue; - } - - value val; - symbol *sym; - int ident = doexpr2( - TRUE, FALSE, FALSE, FALSE, - &type->idxtag[type->numdim], - &sym, 0, &val - ); - - if (ident == iVARIABLE || ident == iEXPRESSION || ident == iARRAYCELL) { - type->size = -1; - type->dim[type->numdim] = 0; - } else if (ident == iCONSTEXPR) { - if (val.constval > 0) { - if (type->size != -1) - type->size = val.constval; - type->dim[type->numdim] = val.constval; - } else { - error(9); - } - if (sym && sym->usage & uENUMROOT) - type->enumroot = sym->dim.enumlist; - type->idxtag[type->numdim] = sym ? sym->tag : 0; - } else { - error(29); - } - - type->numdim++; - needtoken(']'); - } while (matchtoken('[')); - - if (type->size >= 0) { - // Everything was constant. Drop the emitted assembly. - type->ident = iARRAY; - stgdel(staging_index, staging_ptr); - } else { - if (type->tag == pc_tag_string) - stradjust(sPRI); - pushreg(sPRI); - genarray(type->numdim, autozero); - type->ident = iREFARRAY; - type->size = 0; - if (type->is_new) { - // Fixed array with dynamic size. - error(161, pc_typename(type->tag)); - } - } - - stgout(staging_index); - if (!was_staging) - stgset(FALSE); - } else { - do { - if (type->numdim == sDIMEN_MAX) { - error(53); - return; - } - - type->size = needsub(&type->idxtag[type->numdim], enumrootp); - if (type->size > INT_MAX) - error(FATAL_ERROR_INT_OVERFLOW); - - type->dim[type->numdim++] = type->size; - } while (matchtoken('[')); - - type->ident = iARRAY; - } - - decl->type.has_postdims = TRUE; -} - -static int parse_old_decl(declinfo_t *decl, int flags) -{ - token_t tok; - typeinfo_t *type = &decl->type; - - if (matchtoken(tCONST)) { - if (type->usage & uCONST) - error(138); - type->usage |= uCONST; - } - - if (flags & DECLFLAG_ARGUMENT) { - if (matchtoken('&')) - type->ident = iREFERENCE; - - // grammar for multitags is: - // multi-tag ::= '{' (symbol (',' symbol)*)? '}' ':' - if (matchtoken('{')) { - while (type->numtags < MAXTAGS) { - int tag = 0; - - if (!matchtoken('_')) { - // If we don't get the magic tag '_', then we should have a symbol. - if (expecttoken(tSYMBOL, &tok)) - tag = pc_addtag(tok.str); - } - type->tags[type->numtags++] = tag; - - if (matchtoken('}')) - break; - needtoken(','); - } - needtoken(':'); - } - if (type->numtags > 1) - error(158); - } - - if (type->numtags == 0) { - if (matchtoken2(tLABEL, &tok)) - type->tags[type->numtags++] = pc_addtag(tok.str); - else - type->tags[type->numtags++] = 0; - } - - // All finished with tag stuff. - type->tag = type->tags[0]; - - // Look for varargs and end early. - if (matchtoken(tELLIPS)) { - type->ident = iVARARGS; - return TRUE; - } - - if (flags & DECLMASK_NAMED_DECL) { - if ((flags & DECLFLAG_MAYBE_FUNCTION) && matchtoken(tOPERATOR)) { - decl->opertok = operatorname(decl->name); - if (decl->opertok == 0) - strcpy(decl->name, "__unknown__"); - } else { - if (!lexpeek(tSYMBOL)) { - extern const char *sc_tokens[]; - switch (lextok(&tok)) { - case tOBJECT: - case tCHAR: - case tVOID: - case tINT: - if (lexpeek(tSYMBOL)) { - error(143); - } else { - error(157, sc_tokens[tok.id - tFIRST]); - strcpy(decl->name, sc_tokens[tok.id - tFIRST]); - } - break; - default: - lexpush(); - break; - } - } - if (expecttoken(tSYMBOL, &tok)) - strcpy(decl->name, tok.str); - else if (decl->name[0] == '\0') - strcpy(decl->name, "__unknown__"); - } - } - - if ((flags & DECLMASK_NAMED_DECL) && !decl->opertok) { - if (matchtoken('[')) - parse_old_array_dims(decl, flags); - } - - if (sc_require_newdecls) - error(147); - - return TRUE; -} - -static int reparse_old_decl(declinfo_t *decl, int flags) -{ - int usage = decl->type.usage & uCONST; - - memset(decl, 0, sizeof(*decl)); - decl->type.ident = iVARIABLE; - decl->type.size = 1; - decl->type.usage |= usage; - - return parse_old_decl(decl, flags); -} - -static int parse_new_decl(declinfo_t *decl, const token_t *first, int flags) -{ - token_t tok; - - if (!parse_new_typeexpr(&decl->type, first, flags)) - return FALSE; - - decl->type.is_new = TRUE; - - if (flags & DECLMASK_NAMED_DECL) { - if ((flags & DECLFLAG_ARGUMENT) && matchtoken(tELLIPS)) { - decl->type.ident = iVARARGS; - return TRUE; - } - - if ((flags & DECLFLAG_MAYBE_FUNCTION) && matchtoken(tOPERATOR)) { - decl->opertok = operatorname(decl->name); - if (decl->opertok == 0) - strcpy(decl->name, "__unknown__"); - } else { - if (!expecttoken(tSYMBOL, &tok)) { - strcpy(decl->name, "__unknown__"); - return FALSE; - } - strcpy(decl->name, tok.str); - } - } - - if (flags & DECLMASK_NAMED_DECL) { - if (matchtoken('[')) { - if (decl->type.numdim == 0) - parse_old_array_dims(decl, flags); - else - error(121); - } - } - - return TRUE; -} - -static int reparse_new_decl(declinfo_t *decl, int flags) -{ - token_t tok; - if (expecttoken(tSYMBOL, &tok)) - strcpy(decl->name, tok.str); - - if (decl->type.has_postdims) { - // We have something like: - // int x[], y... - // - // Reset the fact that we saw an array. - decl->type.numdim = 0; - decl->type.size = 0; - decl->type.enumroot = NULL; - decl->type.ident = iVARIABLE; - decl->type.size = 0; - decl->type.has_postdims = false; - if (matchtoken('[')) - parse_old_array_dims(decl, flags); - } else { - if (matchtoken('[')) { - if (decl->type.numdim > 0) - error(121); - parse_old_array_dims(decl, flags); - } else if (decl->type.numdim) { - // Reset dimension sizes. - memset(decl->type.dim, 0, sizeof(decl->type.dim[0]) * decl->type.numdim); - } - } - - return TRUE; -} - -// Parse a declaration. -// -// Grammar for named declarations is: -// "const"? symbol ('[' ']')* '&'? symbol -// | "const"? label? '&'? symbol '[' ']' -// -int parse_decl(declinfo_t *decl, int flags) -{ - token_ident_t ident; - - memset(decl, 0, sizeof(*decl)); - - decl->type.ident = iVARIABLE; - decl->type.size = 1; - - // Match early varargs as old decl. - if (lexpeek(tELLIPS)) - return parse_old_decl(decl, flags); - - // Must attempt to match const first, since it's a common prefix. - if (matchtoken(tCONST)) - decl->type.usage |= uCONST; - - // Sometimes we know ahead of time whether the declaration will be old, for - // example, if preceded by tNEW or tDECL. - if (flags & DECLFLAG_OLD) - return parse_old_decl(decl, flags); - if (flags & DECLFLAG_NEW) - return parse_new_decl(decl, NULL, flags); - - // If parsing an argument, there are two simple checks for whether this is a - // new or old-style declaration. - if ((flags & DECLFLAG_ARGUMENT) && (lexpeek('&') || lexpeek('{'))) - return parse_old_decl(decl, flags); - - // Another dead giveaway is there being a label or typeless operator. - if (lexpeek(tLABEL) || lexpeek(tOPERATOR)) - return parse_old_decl(decl, flags); - - // Otherwise, we have to eat a symbol to tell. - if (matchsymbol(&ident)) { - if (lexpeek(tSYMBOL) || - lexpeek(tOPERATOR) || - lexpeek('&') || - lexpeek(tELLIPS)) - { - // A new-style declaration only allows array dims or a symbol name, so - // this is a new-style declaration. - return parse_new_decl(decl, &ident.tok, flags); - } - - if ((flags & DECLMASK_NAMED_DECL) && matchtoken('[')) { - // Oh no - we have to parse array dims before we can tell what kind of - // declarator this is. It could be either: - // "x[] y" (new-style), or - // "y[]," (old-style) - parse_old_array_dims(decl, flags); - - if (matchtoken(tSYMBOL) || matchtoken('&')) { - // This must be a newdecl, "x[] y" or "x[] &y", the latter of which - // is illegal, but we flow it through the right path anyway. - lexpush(); - decl->type.has_postdims = false; - return parse_new_decl(decl, &ident.tok, flags); - } - - // The most basic - "x[]" and that's it. Well, we know it has no tag and - // we know its name. We might as well just complete the entire decl. - strcpy(decl->name, ident.name); - decl->type.tags[decl->type.numtags++] = 0; - decl->type.tag = decl->type.tags[0]; - return TRUE; - } - - // Give the symbol back to the lexer. This is an old decl. - lexpush(); - return parse_old_decl(decl, flags); - } - - // All else has failed. Probably got a type keyword. New-style. - return parse_new_decl(decl, NULL, flags); -} - -static void check_void_decl(const declinfo_t *decl, int variable) -{ - if (decl->type.tag != pc_tag_void) - return; - - if (variable) { - error(144); - return; - } - - if (decl->type.numdim > 0) { - error(145); - return; - } -} - -// Current lexer position is, we've parsed "public", an optional "native", and -// a type expression. -// -// This returns true if there is a method bind, i.e. "() = Y". -static int match_method_bind() -{ - // The grammar here is a little complicated. We must differentiate - // between two different rules: - // public X() = Y; - // public X() { ... - // - // If we parse up to '=', then it becomes harder to call newfunc() later, - // since ideally we'd like to back up to the '('. To work around this we - // use a hacked in lexer API to push older tokens back into the token - // stream. - token_t tok; - if (lextok(&tok) != '(') { - lexpush(); - return FALSE; - } - - if (!matchtoken(')')) { - lexpush(); - return FALSE; - } - - if (!matchtoken('=')) { - lexpush(); - lexpush(); - return FALSE; - } - - return TRUE; -} - -// If a name is too long, error and truncate. -void check_name_length(char *original) -{ - if (strlen(original) > sNAMEMAX) { - char buffer[METHOD_NAMEMAX + 1]; - strcpy(buffer, original); - buffer[sNAMEMAX] = '\0'; - error(123, original, buffer); - original[sNAMEMAX] = '\0'; - } -} - -static void make_primitive(typeinfo_t *type, int tag) -{ - memset(type, 0, sizeof(*type)); - type->tag = tag; - type->tags[type->numtags++] = type->tag; - type->ident = iVARIABLE; -} - -symbol *parse_inline_function(methodmap_t *map, - const typeinfo_t *type, - const char *name, - int is_native, - int is_ctor, - int is_dtor, - bool is_static) -{ - declinfo_t decl; - memset(&decl, 0, sizeof(decl)); - - if (is_dtor) { - make_primitive(&decl.type, pc_tag_void); - } else if (is_ctor) { - make_primitive(&decl.type, map->tag); - } else { - decl.type = *type; - } - decl.type.is_new = TRUE; - - const int *thistag = NULL; - if (!is_ctor && !is_static) - thistag = &map->tag; - - // Build a new symbol. Construct a temporary name including the class. - char fullname[METHOD_NAMEMAX + 1]; - strcpy(fullname, map->name); - strcat(fullname, "."); - strcat(fullname, name); - check_name_length(fullname); - strcpy(decl.name, fullname); - - symbol *target = NULL; - if (is_native) { - target = funcstub(tMETHODMAP, &decl, thistag); - } else { - int lcl_require_newdecls = sc_require_newdecls; - - sc_require_newdecls = TRUE; - int ok = newfunc(&decl, thistag, FALSE, FALSE, TRUE, &target); - sc_require_newdecls = lcl_require_newdecls; - - if (!ok) - return NULL; - if (!target || (target->usage & uFORWARD)) { - error(10); - return NULL; - } - } - return target; -} - -int check_this_tag(methodmap_t *map, symbol *target) -{ - // Check the implicit this parameter. Currently we only allow scalars. As - // to not encourage enum-structs, we will not allow those either. - const arginfo *first_arg = &target->dim.arglist[0]; - if (first_arg->ident == 0 || - first_arg->ident != iVARIABLE || - first_arg->hasdefault || - first_arg->numtags != 1) - { - return FALSE; - } - - // Ensure the methodmap tag is compatible with |this|. - int ok = FALSE; - for (methodmap_t *mapptr = map; mapptr; mapptr = mapptr->parent) { - if (first_arg->tags[0] == mapptr->tag) { - ok = TRUE; - break; - } - } - return ok; -} - -int parse_property_accessor(const typeinfo_t *type, methodmap_t *map, methodmap_method_t *method) -{ - token_ident_t ident; - int is_native = FALSE; - - needtoken(tPUBLIC); - if (!matchsymbol(&ident)) { - if (!matchtoken(tNATIVE)) { - error(125); - return FALSE; - } - is_native = TRUE; - if (!needsymbol(&ident)) - return FALSE; - } - - int getter = (strcmp(ident.name, "get") == 0); - int setter = (strcmp(ident.name, "set") == 0); - - if (!getter && !setter) { - error(125); - return FALSE; - } - - symbol *target = NULL; - - token_ident_t bindsource; - int is_bind = match_method_bind(); - if (is_bind) { - if (!needsymbol(&bindsource)) - return FALSE; - } - - if (is_bind) { - // Find an existing symbol. - target = findglb(bindsource.name, sGLOBAL); - if (!target) - error(17, bindsource.name); - else if (target->ident != iFUNCTN) - error(10); - } else { - typeinfo_t voidtype; - char tmpname[METHOD_NAMEMAX + 1]; - strcpy(tmpname, method->name); - if (getter) - strcat(tmpname, ".get"); - else - strcat(tmpname, ".set"); - - const typeinfo_t *ret_type; - if (getter) { - ret_type = type; - } else { - make_primitive(&voidtype, pc_tag_void); - ret_type = &voidtype; - } - - target = parse_inline_function(map, ret_type, tmpname, is_native, FALSE, FALSE, false); - } - - if (!target) - return FALSE; - - if (getter && method->getter) { - error(126, "getter", method->name); - return FALSE; - } - if (setter && method->setter) { - error(126, "setter", method->name); - return FALSE; - } - - if (getter) { - method->getter = target; - - // Cannot have extra arguments. - if (target->dim.arglist[0].ident && target->dim.arglist[1].ident) - error(127); - - if (!check_this_tag(map, target)) { - error(108, layout_spec_name(map->spec), map->name); - return FALSE; - } - - // Must return the same tag as the property. - if (type->tag != target->tag) { - const char *kind = getter ? "getter" : "setter"; - error(128, "getter", map->name, type_to_name(type->tag)); - } - } else { - method->setter = target; - - if (!check_this_tag(map, target)) { - error(108, layout_spec_name(map->spec), map->name); - return FALSE; - } - - // Must have one extra argument taking the return type. - arginfo *arg = &target->dim.arglist[1]; - if (arg->ident != iVARIABLE || - arg->hasdefault || - arg->numtags != 1 || - arg->tags[0] != type->tag) - { - error(150, pc_tagname(type->tag)); - return FALSE; - } - if (target->dim.arglist[2].ident) { - error(150, pc_tagname(type->tag)); - return FALSE; - } - if (target->tag != pc_tag_void) - error(151); - } - - require_newline(is_bind || (target->usage & uNATIVE)); - return TRUE; -} - -methodmap_method_t *parse_property(methodmap_t *map) -{ - typeinfo_t type; - token_ident_t ident; - methodmap_method_t *method; - - memset(&type, 0, sizeof(type)); - if (!parse_new_typeexpr(&type, NULL, 0)) - return NULL; - if (!needsymbol(&ident)) - return NULL; - - method = (methodmap_method_t *)calloc(1, sizeof(methodmap_method_t)); - strcpy(method->name, ident.name); - method->target = NULL; - method->getter = NULL; - method->setter = NULL; - - if (matchtoken('{')) { - while (!matchtoken('}')) { - if (!parse_property_accessor(&type, map,method)) - lexclr(TRUE); - } - - require_newline(FALSE); - } - - return method; -} - -methodmap_method_t *parse_method(methodmap_t *map) -{ - int maybe_ctor = 0; - int is_ctor = 0; - int is_dtor = 0; - int is_bind = 0; - int is_native = 0; - bool is_static = false; - const char *spectype = layout_spec_name(map->spec); - - if (matchtoken(tSTATIC)) - is_static = true; - - // This stores the name of the method (for destructors, we add a ~). - token_ident_t ident; - strcpy(ident.name, "__unknown__"); - - // For binding syntax, like X() = Y, this stores the right-hand name. - token_ident_t bindsource; - strcpy(bindsource.name, "__unknown__"); - - typeinfo_t type; - memset(&type, 0, sizeof(type)); - - // Destructors cannot be static. - if (!is_static && matchtoken('~')) { - // We got something like "public ~Blah = X" - is_bind = TRUE; - is_dtor = TRUE; - if (!needsymbol(&ident)) - return NULL; - if (!needtoken('(')) - return NULL; - if (!needtoken(')')) - return NULL; - if (!needtoken('=')) - return NULL; - if (!needsymbol(&bindsource)) - return NULL; - } else { - int got_symbol; - - is_native = matchtoken(tNATIVE); - got_symbol = matchsymbol(&ident); - - if (!is_native && got_symbol) { - // We didn't see "native", but we saw a symbol. Match for '() =' which - // would indicate a method bind. - is_bind = match_method_bind(); - - if (is_bind) { - // If we saw "X() =", then grab the right-hand name. - if (!needsymbol(&bindsource)) - return NULL; - } - } - - if (!is_bind) { - // All we know at this point is that we do NOT have a method bind. Keep - // pattern matching for an inline constructor, destructor, or method. - if (!got_symbol && matchtoken('~')) { - // ::= '~' ident - is_dtor = TRUE; - if (!needsymbol(&ident)) - return NULL; - } else if (got_symbol && matchtoken('(')) { - // ::= ident '(' - - // Push the '(' token back for declargs(). - maybe_ctor = TRUE; - lexpush(); - } else { - // The first token of the type expression is either the symbol we - // predictively parsed earlier, or it's been pushed back into the - // lex buffer. - const token_t *first = got_symbol ? &ident.tok : NULL; - - // Parse for type expression, priming it with the token we predicted - // would be an identifier. - if (!parse_new_typeexpr(&type, first, 0)) - return NULL; - - // Now, we should get an identifier. - if (!needsymbol(&ident)) - return NULL; - - // If the identifier is a constructor, error, since the user specified - // a type. - if (strcmp(ident.name, map->name) == 0) - error(99, "constructor"); - } - } else { - is_ctor = (strcmp(ident.name, map->name) == 0); - } - } // if (matchtoken('~')) - - // Do some preliminary verification of ctor/dtor names. - if (is_dtor) { - if (strcmp(ident.name, map->name) != 0) - error(114, "destructor", spectype, map->name); - - // Make sure the final name has "~" in it. - strcpy(ident.name, "~"); - strcat(ident.name, map->name); - check_name_length(ident.name); - } else if (maybe_ctor) { - if (strcmp(ident.name, map->name) == 0) - is_ctor = TRUE; - else - error(114, "constructor", spectype, map->name); - } - - if (is_ctor && is_static) { - // Constructors may not be static. - error(175); - } - - symbol *target = NULL; - if (is_bind) { - // Find an existing symbol. - target = findglb(bindsource.name, sGLOBAL); - if (!target) - error(17, bindsource.name); - else if (target->ident != iFUNCTN) - error(10); - } else { - target = parse_inline_function(map, &type, ident.name, is_native, is_ctor, is_dtor, is_static); - } - - if (!target) - return NULL; - - // Verify destructor targets. - if (is_dtor) { - if (!(target->usage & uNATIVE)) { - // Must be a native. - error(118); - return NULL; - } - - if (target->tag != 0 && target->tag != pc_tag_void) { - // Cannot return a value. - error(99, "destructor"); - return NULL; - } - - if (target->dim.arglist[0].ident && target->dim.arglist[1].ident) { - // Cannot have extra arguments. - error(119); - return NULL; - } - } - - // Verify constructor targets. - if (is_ctor) { - if (target->tag != map->tag) - error(112, map->name); - } - - methodmap_method_t *method = (methodmap_method_t *)calloc(1, sizeof(methodmap_method_t)); - strcpy(method->name, ident.name); - method->target = target; - method->getter = NULL; - method->setter = NULL; - method->is_static = is_static; - - // If the symbol is a constructor, we bypass the initial argument checks. - if (is_ctor) { - if (map->ctor) - error(113, map->name); - } else if (!is_static) { - if (!check_this_tag(map, target)) - error(108, spectype, map->name); - } - - if (is_dtor) - map->dtor = method; - if (is_ctor) - map->ctor = method; - - require_newline(is_bind || (target->usage & uNATIVE)); - return method; -} - -/** - * domethodmap - declare a method map for OO-ish syntax. - * - */ -static void domethodmap(LayoutSpec spec) -{ - int val; - char *str; - methodmap_t *parent = NULL; - const char *spectype = layout_spec_name(spec); - - // methodmap ::= "methodmap" symbol ("<" symbol)? "{" methodmap-body "}" - char mapname[sNAMEMAX + 1]; - if (lex(&val, &str) != tSYMBOL) - error(93); - strcpy(mapname, str); - - if (!isupper(*mapname)) - error(109, spectype); - - LayoutSpec old_spec = deduce_layout_spec_by_name(mapname); - int can_redef = can_redef_layout_spec(spec, old_spec); - if (!can_redef) - error(110, mapname, layout_spec_name(old_spec)); - - if (matchtoken('<')) { - if (lex(&val, &str) != tSYMBOL) { - error(93); - return; - } - - if ((parent = methodmap_find_by_name(str)) == NULL) { - error(102, spectype, str); - } else if (parent->spec != spec) { - error(129); - } - } - - methodmap_t *map = (methodmap_t *)calloc(1, sizeof(methodmap_t)); - map->parent = parent; - map->spec = spec; - strcpy(map->name, mapname); - if (spec == Layout_MethodMap) { - map->tag = pc_addtag_flags(mapname, FIXEDTAG | METHODMAPTAG); - - if (matchtoken(tNULLABLE) || (parent && parent->nullable)) - map->nullable = TRUE; - } else { - map->tag = pc_addtag_flags(mapname, FIXEDTAG | OBJECTTAG); - } - methodmap_add(map); - - if (can_redef) { - symbol *sym = findglb(mapname, sGLOBAL); - if (sym && sym->ident != iMETHODMAP) { - // We should only hit this on the first pass. Assert really hard that - // we're about to kill an enum definition and not something random. - assert(sc_status == statFIRST); - assert(sym->ident == iCONSTEXPR); - assert(TAGID(map->tag) == TAGID(sym->tag)); - - sym->ident = iMETHODMAP; - - // Kill previous enumstruct properties, if any. - if (sym->usage & uENUMROOT) { - for (constvalue *cv = sym->dim.enumlist; cv; cv = cv->next) { - symbol *csym = findglb(cv->name, sGLOBAL); - if (csym && - csym->ident == iCONSTEXPR && - csym->parent == sym && - (csym->usage & uENUMFIELD)) - { - csym->usage &= ~uENUMFIELD; - csym->parent = NULL; - } - } - delete_consttable(sym->dim.enumlist); - free(sym->dim.enumlist); - sym->dim.enumlist = NULL; - } - } else if (!sym) { - sym = addsym( - mapname, // name - 0, // addr - iMETHODMAP, // ident - sGLOBAL, // vclass - map->tag, // tag - uDEFINE); // usage - } - sym->methodmap = map; - } - - needtoken('{'); - while (!matchtoken('}')) { - token_t tok; - methodmap_method_t **methods; - methodmap_method_t *method = NULL; - - if (lextok(&tok) == tPUBLIC) { - method = parse_method(map); - } else if (tok.id == tSYMBOL && strcmp(tok.str, "property") == 0) { - method = parse_property(map); - } else { - error(124); - } - - if (method) { - // Check that a method with this name doesn't already exist. - for (size_t i = 0; i < map->nummethods; i++) { - if (strcmp(map->methods[i]->name, method->name) == 0) { - error(103, method->name, spectype); - method = NULL; - break; - } - } - } - - if (!method) { - if (!consume_line()) - return; - continue; - } - - methods = (methodmap_method_t **)realloc(map->methods, sizeof(methodmap_method_t *) * (map->nummethods + 1)); - if (!methods) { - error(FATAL_ERROR_OOM); - return; - } - map->methods = methods; - map->methods[map->nummethods++] = method; - } - - require_newline(TRUE); -} - -class AutoStage -{ - public: - AutoStage() : lcl_staging_(FALSE) - { - if (!staging) { - stgset(TRUE); - lcl_staging_ = TRUE; - lcl_stgidx_ = stgidx; - assert(stgidx == 0); - } - } - ~AutoStage() { - if (lcl_staging_) { - stgout(lcl_stgidx_); - stgset(FALSE); - } - } - - private: - int lcl_staging_; - int lcl_stgidx_; -}; - -// delete ::= "delete" expr -static void dodelete() -{ - AutoStage staging_on; - - svalue sval; - int ident = lvalexpr(&sval); - needtoken(tTERM); - - switch (ident) { - case iFUNCTN: - case iREFFUNC: - error(167, "functions"); - return; - - case iARRAY: - case iREFARRAY: - case iARRAYCELL: - case iARRAYCHAR: - { - symbol *sym = sval.val.sym; - if (!sym || sym->dim.array.level > 0) { - error(167, "arrays"); - return; - } - break; - } - } - - if (sval.val.tag == 0) { - error(167, "integers"); - return; - } - - methodmap_t *map = methodmap_find_by_tag(sval.val.tag); - if (!map) { - error(115, "type", pc_tagname(sval.val.tag)); - return; - } - - { - methodmap_t *iter = map; - while (iter) { - if (iter->dtor) { - map = iter; - break; - } - iter = iter->parent; - } - } - - if (!map || !map->dtor) { - error(115, layout_spec_name(map->spec), map->name); - return; - } - - // Only zap non-const lvalues. - int zap = sval.lvalue; - if (zap && sval.val.sym && (sval.val.sym->usage & uCONST)) - zap = FALSE; - - int popaddr = FALSE; - methodmap_method_t *accessor = NULL; - if (sval.lvalue) { - if (zap) { - switch (sval.val.ident) { - case iACCESSOR: - // rvalue() removes iACCESSOR so we store it locally. - accessor = sval.val.accessor; - if (!accessor->setter) { - zap = FALSE; - break; - } - pushreg(sPRI); - popaddr = TRUE; - break; - case iARRAYCELL: - case iARRAYCHAR: - pushreg(sPRI); - popaddr = TRUE; - break; - } - } - - rvalue(&sval.val); - } - - // push.pri - // push.c 1 - // sysreq.c N 1 - // stack 8 - pushreg(sPRI); - { - pushval(1); - ffcall(map->dtor->target, NULL, 1); - - // Only mark usage if we're not skipping codegen. - if (sc_status != statSKIP) - markusage(map->dtor->target, uREAD); - } - - if (zap) { - if (popaddr) - popreg(sALT); - - // Store 0 back. - ldconst(0, sPRI); - if (accessor) - invoke_setter(accessor, FALSE); - else - store(&sval.val); - } - - markexpr(sEXPR, NULL, 0); -} - -/** - * function-type ::= "(" function-type-inner ")" - * | function-type-inner - * function-type-inner ::= "function" type-expr "(" new-style-args ")" - */ -static void parse_function_type(functag_t *type) -{ - memset(type, 0, sizeof(*type)); - - int lparen = matchtoken('('); - needtoken(tFUNCTION); - - parse_new_typename(NULL, &type->ret_tag); - type->usage = uPUBLIC; - - needtoken('('); - - while (!matchtoken(')')) { - declinfo_t decl; - - // Initialize. - memset(&decl, 0, sizeof(decl)); - decl.type.ident = iVARIABLE; - - parse_new_decl(&decl, NULL, DECLFLAG_ARGUMENT); - - // Eat optional symbol name. - matchtoken(tSYMBOL); - - // Error once when we're past max args. - if (type->argcount == sARGS_MAX) { - error(45); - continue; - } - - // Account for strings. - fix_char_size(&decl); - - funcarg_t *arg = &type->args[type->argcount++]; - arg->tagcount = 1; - arg->tags[0] = decl.type.tag; - arg->dimcount = decl.type.numdim; - memcpy(arg->dims, decl.type.dim, arg->dimcount * sizeof(decl.type.dim[0])); - arg->fconst = (decl.type.usage & uCONST) ? TRUE : FALSE; - if (decl.type.ident == iARRAY) - arg->ident = iREFARRAY; - else - arg->ident = decl.type.ident; - - if (!matchtoken(',')) { - needtoken(')'); - break; - } - } - - if (lparen) - needtoken(')'); - - require_newline(TRUE); - errorset(sRESET, 0); -} - -static void dotypedef() -{ - token_ident_t ident; - if (!needsymbol(&ident)) - return; - - int prev_tag = pc_findtag(ident.name); - if (prev_tag != -1 && !(prev_tag & FUNCTAG)) - error(94); - - needtoken('='); - - funcenum_t *def = funcenums_add(ident.name); - - functag_t type; - parse_function_type(&type); - functags_add(def, &type); -} - -// Unsafe typeset - only supports function types. This is a transition hack for SP2. -static void dotypeset() -{ - token_ident_t ident; - if (!needsymbol(&ident)) - return; - - int prev_tag = pc_findtag(ident.name); - if (prev_tag != -1 && !(prev_tag & FUNCTAG)) - error(94); - - funcenum_t *def = funcenums_add(ident.name); - needtoken('{'); - while (!matchtoken('}')) { - functag_t type; - parse_function_type(&type); - functags_add(def, &type); - } - - require_newline(TRUE); -} - -/** - * dofuncenum - declare function enumerations - */ -static void dofuncenum(int listmode) -{ - cell val; - char *str; - // char *ptr; - char tagname[sNAMEMAX+1]; - constvalue *cur; - funcenum_t *fenum = NULL; - int i; - int newStyleTag = 0; - int isNewStyle = 0; - - /* get the explicit tag (required!) */ - int l = lex(&val,&str); - if (l != tSYMBOL) { - if (listmode == FALSE && l == tPUBLIC) { - isNewStyle = TRUE; - switch (lex(&val, &str)) { - case tOBJECT: - newStyleTag = pc_tag_object; - break; - case tINT: - newStyleTag = 0; - break; - case tVOID: - newStyleTag = pc_tag_void; - break; - case tCHAR: - newStyleTag = pc_tag_string; - break; - case tLABEL: - newStyleTag = pc_addtag(str); - break; - case tSYMBOL: - // Check whether this is new-style declaration. - // we'll port this all to parse_decl() sometime. - if (lexpeek('(')) - lexpush(); - else - newStyleTag = pc_addtag(str); - break; - default: - error(93); - } - - if (!needtoken(tSYMBOL)) { - lexclr(TRUE); - litidx = 0; - return; - } - l = tokeninfo(&val, &str); - } else { - error(93); - } - } - - /* This tag can't already exist! */ - cur=tagname_tab.next; - while (cur) { - if (strcmp(cur->name, str) == 0) { - /* Another bad one... */ - if (!(cur->value & FUNCTAG)) - error(94); - break; - } - cur = cur->next; - } - strcpy(tagname, str); - - fenum = funcenums_add(tagname); - - if (listmode) - needtoken('{'); - do { - functag_t func; - if (listmode && matchtoken('}')) { - /* Quick exit */ - lexpush(); - break; - } - memset(&func, 0, sizeof(func)); - if (!isNewStyle) { - func.ret_tag = pc_addtag(NULL); /* Get the return tag */ - l = lex(&val, &str); - /* :TODO: - * Right now, there is a problem. We can't pass non-public function pointer addresses around, - * because the address isn't known until the final reparse. Unfortunately, you can write code - * before the address is known, because Pawn's compiler isn't truly multipass. - * - * When you call a function, there's no problem, because it does not write the address. - * The assembly looks like this: - * call MyFunction - * Then, only at assembly time (once all passes are done), does it know the address. - * I do not see any solution to this because there is no way I know to inject the function name - * rather than the constant value. And even if we could, we'd have to change the assembler recognize that. - */ - if (l == tPUBLIC) { - func.usage = uPUBLIC; - } else { - error(1, "-public-", str); - } - } else { - func.ret_tag = newStyleTag; - func.usage = uPUBLIC; - } - needtoken('('); - do { - funcarg_t *arg = &(func.args[func.argcount]); - - /* Quick exit */ - if (matchtoken(')')) { - lexpush(); - break; - } - l = lex(&val, &str); - if (l == '&') { - if ((arg->ident != iVARIABLE && arg->ident != 0) || arg->tagcount > 0) - error(1, "-identifier-", "&"); - arg->ident = iREFERENCE; - } else if (l == tCONST) { - if ((arg->ident != iVARIABLE && arg->ident != 0) || arg->tagcount > 0) - error(1, "-identifier-", "const"); - arg->fconst=TRUE; - } else if (l == tLABEL) { - if (arg->tagcount > 0) - error(1, "-identifier-", "-tagname-"); - arg->tags[arg->tagcount++] = pc_addtag(str); - l=tLABEL; - } else if (l == tSYMBOL) { - if (func.argcount >= sARGS_MAX) - error(45); - if (str[0] == PUBLIC_CHAR) - error(56, str); - if (matchtoken('[')) - { - cell size; - if (arg->ident == iREFERENCE) - error(67, str); - do { - constvalue *enumroot; - int ignore_tag; - if (arg->dimcount == sDIMEN_MAX) { - error(53); - break; - } - size = needsub(&ignore_tag, &enumroot); - arg->dims[arg->dimcount] = size; - arg->dimcount += 1; - } while (matchtoken('[')); - /* Handle strings */ - if ((arg->tagcount == 1 && arg->tags[0] == pc_tag_string) - && arg->dims[arg->dimcount-1]) - { - arg->dims[arg->dimcount-1] = (size + sizeof(cell)-1) / sizeof(cell); - } - arg->ident=iREFARRAY; - } else if (arg->ident == 0) { - arg->ident = iVARIABLE; - } - - if (matchtoken('=')) { - needtoken('0'); - arg->ommittable = TRUE; - func.ommittable = TRUE; - } else if (func.ommittable) { - error(95); - } - func.argcount++; - } else if (l == tELLIPS) { - if (arg->ident == iVARIABLE) - error(10); - arg->ident = iVARARGS; - func.argcount++; - } else { - error(10); - } - } while (l == '&' || l == tLABEL || l == tCONST || (l != tELLIPS && matchtoken(','))); - needtoken(')'); - for (i=0; i0) - multiplier*=2; - } /* if */ - needtoken(')'); - } /* if */ - - if (strlen(enumname)>0) { - if (vclass == sGLOBAL) { - if ((enumsym = findglb(enumname, vclass)) != NULL) { - // If we were previously defined as a methodmap, don't overwrite the - // symbol. Otherwise, flow into add_constant where we will error. - if (enumsym->ident != iMETHODMAP) - enumsym = nullptr; - } - } - - if (!enumsym) { - /* create the root symbol, so the fields can have it as their "parent" */ - enumsym=add_constant(enumname,0,vclass,tag); - if (enumsym!=NULL) - enumsym->usage |= uENUMROOT; - /* start a new list for the element names */ - if ((enumroot=(constvalue*)malloc(sizeof(constvalue)))==NULL) - error(FATAL_ERROR_OOM); /* insufficient memory (fatal error) */ - memset(enumroot,0,sizeof(constvalue)); - } - } else { - enumsym=NULL; - enumroot=NULL; - } /* if */ - - // If this enum is for a methodmap, forget the symbol so code below doesn't - // build an enum struct. - if (enumsym && enumsym->ident == iMETHODMAP) - enumsym = NULL; - - needtoken('{'); - /* go through all constants */ - value=0; /* default starting value */ - do { - int idxtag,fieldtag; - symbol *sym; - if (matchtoken('}')) { /* quick exit if '}' follows ',' */ - lexpush(); - break; - } /* if */ - idxtag=pc_addtag(NULL); /* optional explicit item tag */ - if (needtoken(tSYMBOL)) { /* read in (new) token */ - tokeninfo(&val,&str); /* get the information */ - strcpy(constname,str); /* save symbol name */ - } else { - constname[0]='\0'; - } /* if */ - size=increment; /* default increment of 'val' */ - fieldtag=0; /* default field tag */ - if (matchtoken('[')) { - exprconst(&size,&fieldtag,NULL); /* get size */ - needtoken(']'); - } /* if */ - /* :TODO: do we need a size modifier here for pc_tag_string? */ - if (matchtoken('=')) - exprconst(&value,NULL,NULL); /* get value */ - /* add_constant() checks whether a variable (global or local) or - * a constant with the same name already exists - */ - sym=add_constant(constname,value,vclass,tag); - if (sym==NULL) - continue; /* error message already given */ - /* set the item tag and the item size, for use in indexing arrays */ - sym->x.tags.index=idxtag; - sym->x.tags.field=fieldtag; - sym->dim.array.length=size; - sym->dim.array.level=0; - sym->dim.array.slength=0; - sym->parent=enumsym; - /* add the constant to a separate list as well */ - if (enumroot!=NULL) { - sym->usage |= uENUMFIELD; - append_constval(enumroot,constname,value,tag); - } /* if */ - if (multiplier==1) - value+=size; - else - value*=size*multiplier; - } while (matchtoken(',')); - needtoken('}'); /* terminates the constant list */ - matchtoken(';'); /* eat an optional ; */ - - /* set the enum name to the "next" value (typically the last value plus one) */ - if (enumsym) { - assert((enumsym->usage & uENUMROOT)!=0); - enumsym->addr=value; - /* assign the constant list */ - assert(enumroot!=NULL); - enumsym->dim.enumlist=enumroot; - sc_attachdocumentation(enumsym); /* attach any documenation to the enumeration */ - } /* if */ -} - -static int getstates(const char *funcname) -{ - char fsaname[sNAMEMAX+1],statename[sNAMEMAX+1]; - cell val; - char *str; - constvalue *automaton; - constvalue *state; - int fsa,islabel; - int *list; - int count,listsize,state_id; - - if (!matchtoken('<')) - return 0; - if (matchtoken('>')) - return -1; /* special construct: all other states (fall-back) */ - - count=0; - listsize=0; - list=NULL; - fsa=-1; - - do { - if (!(islabel=matchtoken(tLABEL)) && !needtoken(tSYMBOL)) - break; - tokeninfo(&val,&str); - assert(strlen(str)=0 && automaton->index!=fsa) - error(83,funcname); /* multiple automatons for a single function/variable */ - fsa=automaton->index; - } /* if */ - state=state_add(statename,fsa); - /* add this state to the state combination list (it will be attached to the - * automaton later) */ - state_buildlist(&list,&listsize,&count,(int)state->value); - } while (matchtoken(',')); - needtoken('>'); - - if (count>0) { - assert(automaton!=NULL); - assert(fsa>=0); - state_id=state_addlist(list,count,fsa); - assert(state_id>0); - } else { - /* error is already given */ - state_id=0; - } /* if */ - if (list!=NULL) - free(list); - - return state_id; -} - -static void attachstatelist(symbol *sym, int state_id) -{ - assert(sym!=NULL); - if ((sym->usage & uDEFINE)!=0 && (sym->states==NULL || state_id==0)) - error(21,sym->name); /* function already defined, either without states or the current definition has no states */ - - if (state_id!=0) { - /* add the state list id */ - constvalue *stateptr; - if (sym->states==NULL) { - if ((sym->states=(constvalue*)malloc(sizeof(constvalue)))==NULL) - error(FATAL_ERROR_OOM); /* insufficient memory (fatal error) */ - memset(sym->states,0,sizeof(constvalue)); - } /* if */ - /* see whether the id already exists (add new state only if it does not - * yet exist - */ - assert(sym->states!=NULL); - for (stateptr=sym->states->next; stateptr!=NULL && stateptr->index!=state_id; stateptr=stateptr->next) - /* nothing */; - assert(state_id<=SHRT_MAX); - if (stateptr==NULL) - append_constval(sym->states,"",code_idx,(short)state_id); - else if (stateptr->value==0) - stateptr->value=code_idx; - else - error(84,sym->name); - /* also check for another conflicting situation: a fallback function - * without any states - */ - if (state_id==-1 && sc_status!=statFIRST) { - /* in the second round, all states should have been accumulated */ - assert(sym->states!=NULL); - for (stateptr=sym->states->next; stateptr!=NULL && stateptr->index==-1; stateptr=stateptr->next) - /* nothing */; - if (stateptr==NULL) - error(85,sym->name); /* no states are defined for this function */ - } /* if */ - } /* if */ -} - -// This simpler version of matchtag() only checks whether two tags represent -// the same type. Because methodmaps are attached to types and are not actually -// types themselves, we strip out the methodmap bit in case a methodmap was -// seen later than another instance of a tag. -static int compare_tag(int tag1, int tag2) -{ - return (tag1 & (~METHODMAPTAG)) == (tag2 & (~METHODMAPTAG)); -} - -/* - * Finds a function in the global symbol table or creates a new entry. - * It does some basic processing and error checking. - */ -symbol *fetchfunc(char *name) -{ - symbol *sym; - - if ((sym=findglb(name,sGLOBAL))!=0) { /* already in symbol table? */ - if (sym->ident!=iFUNCTN) { - error(21,name); /* yes, but not as a function */ - return NULL; /* make sure the old symbol is not damaged */ - } else if ((sym->usage & uNATIVE)!=0) { - error(21,name); /* yes, and it is a native */ - } /* if */ - assert(sym->vclass==sGLOBAL); - } else { - /* don't set the "uDEFINE" flag; it may be a prototype */ - sym=addsym(name,code_idx,iFUNCTN,sGLOBAL,0,0); - assert(sym!=NULL); /* fatal error 103 must be given on error */ - /* assume no arguments */ - sym->dim.arglist=(arginfo*)calloc(1, sizeof(arginfo)); - /* set library ID to NULL (only for native functions) */ - sym->x.lib=NULL; - /* set the required stack size to zero (only for non-native functions) */ - sym->x.stacksize=1; /* 1 for PROC opcode */ - } /* if */ - if (pc_deprecate!=NULL) { - assert(sym!=NULL); - sym->flags|=flgDEPRECATED; - if (sc_status==statWRITE) { - if (sym->documentation!=NULL) { - free(sym->documentation); - sym->documentation=NULL; - } /* if */ - sym->documentation=pc_deprecate; - } else { - free(pc_deprecate); - } /* if */ - pc_deprecate=NULL; - } /* if */ - - return sym; -} - -/* This routine adds symbolic information for each argument. - */ -static void define_args(void) -{ - symbol *sym; - - /* At this point, no local variables have been declared. All - * local symbols are function arguments. - */ - sym=loctab.next; - while (sym!=NULL) { - assert(sym->ident!=iLABEL); - assert(sym->vclass==sLOCAL); - markexpr(sLDECL,sym->name,sym->addr); /* mark for better optimization */ - sym=sym->next; - } /* while */ -} - -static int operatorname(char *name) -{ - int opertok; - char *str; - cell val; - - assert(name!=NULL); - - /* check the operator */ - opertok=lex(&val,&str); - switch (opertok) { - case '+': - case '-': - case '*': - case '/': - case '%': - case '>': - case '<': - case '!': - case '~': - case '=': - name[0]=(char)opertok; - name[1]='\0'; - break; - case tINC: - strcpy(name,"++"); - break; - case tDEC: - strcpy(name,"--"); - break; - case tlEQ: - strcpy(name,"=="); - break; - case tlNE: - strcpy(name,"!="); - break; - case tlLE: - strcpy(name,"<="); - break; - case tlGE: - strcpy(name,">="); - break; - default: - name[0]='\0'; - error(7); /* operator cannot be redefined (or bad operator name) */ - return 0; - } /* switch */ - - return opertok; -} - -static int operatoradjust(int opertok,symbol *sym,char *opername,int resulttag) -{ - int tags[2]={0,0}; - int count=0; - arginfo *arg; - char tmpname[sNAMEMAX+1]; - symbol *oldsym; - - if (opertok==0) - return TRUE; - - assert(sym!=NULL && sym->ident==iFUNCTN && sym->dim.arglist!=NULL); - /* count arguments and save (first two) tags */ - while (arg=&sym->dim.arglist[count], arg->ident!=0) { - if (count<2) { - if (arg->numtags>1) - error(65,count+1); /* function argument may only have a single tag */ - else if (arg->numtags==1) - tags[count]=arg->tags[0]; - } /* if */ - if (opertok=='~' && count==0) { - if (arg->ident!=iREFARRAY) - error(73,arg->name);/* must be an array argument */ - } else { - //if (arg->ident!=iVARIABLE) - //error(66,arg->name);/* must be non-reference argument */ - } /* if */ - if (arg->hasdefault) - error(59,arg->name); /* arguments of an operator may not have a default value */ - count++; - } /* while */ - - /* for '!', '++' and '--', count must be 1 - * for '-', count may be 1 or 2 - * for '=', count must be 1, and the resulttag is also important - * for all other (binary) operators and the special '~' operator, count must be 2 - */ - switch (opertok) { - case '!': - case '=': - case tINC: - case tDEC: - if (count!=1) - error(62); /* number or placement of the operands does not fit the operator */ - break; - case '-': - if (count!=1 && count!=2) - error(62); /* number or placement of the operands does not fit the operator */ - break; - default: - if (count!=2) - error(62); /* number or placement of the operands does not fit the operator */ - } /* switch */ - - if (tags[0]==0 && ((opertok!='=' && tags[1]==0) || (opertok=='=' && resulttag==0))) - error(64); /* cannot change predefined operators */ - - /* change the operator name */ - assert(strlen(opername)>0); - operator_symname(tmpname,opername,tags[0],tags[1],count,resulttag); - if ((oldsym=findglb(tmpname,sGLOBAL))!=NULL) { - int i; - if ((oldsym->usage & uDEFINE)!=0) { - char errname[2*sNAMEMAX+16]; - funcdisplayname(errname,tmpname); - error(21,errname); /* symbol already defined */ - } /* if */ - sym->usage|=oldsym->usage; /* copy flags from the previous definition */ - for (i=0; inumrefers; i++) - if (oldsym->refer[i]!=NULL) - refer_symbol(sym,oldsym->refer[i]); - delete_symbol(&glbtab,oldsym); - } /* if */ - RemoveFromHashTable(sp_Globals, sym); - strcpy(sym->name,tmpname); - sym->hash=NameHash(sym->name);/* calculate new hash */ - AddToHashTable(sp_Globals, sym); - - /* operators should return a value, except the '~' operator */ - if (opertok!='~') - sym->usage |= uRETVALUE; - - return TRUE; -} - -static int check_operatortag(int opertok,int resulttag,char *opername) -{ - assert(opername!=NULL && strlen(opername)>0); - switch (opertok) { - case '!': - case '<': - case '>': - case tlEQ: - case tlNE: - case tlLE: - case tlGE: - if (resulttag!=pc_tag_bool) { - error(63,opername,"bool:"); /* operator X requires a "bool:" result tag */ - return FALSE; - } /* if */ - break; - case '~': - if (resulttag!=0) { - error(63,opername,"_:"); /* operator "~" requires a "_:" result tag */ - return FALSE; - } /* if */ - break; - } /* switch */ - return TRUE; -} - -static char *tag2str(char *dest,int tag) -{ - assert(tag>=0); - sprintf(dest,"0%x",tag); - return isdigit(dest[1]) ? &dest[1] : dest; -} - -char *operator_symname(char *symname,const char *opername,int tag1,int tag2,int numtags,int resulttag) -{ - char tagstr1[10], tagstr2[10]; - int opertok; - - assert(numtags>=1 && numtags<=2); - opertok= (opername[1]=='\0') ? opername[0] : 0; - if (opertok=='=') - sprintf(symname,"%s%s%s",tag2str(tagstr1,resulttag),opername,tag2str(tagstr2,tag1)); - else if (numtags==1 || opertok=='~') - sprintf(symname,"%s%s",opername,tag2str(tagstr1,tag1)); - else - sprintf(symname,"%s%s%s",tag2str(tagstr1,tag1),opername,tag2str(tagstr2,tag2)); - return symname; -} - -static int parse_funcname(char *fname,int *tag1,int *tag2,char *opname) -{ - char *ptr,*name; - int unary; - - /* tags are only positive, so if the function name starts with a '-', - * the operator is an unary '-' or '--' operator. - */ - if (*fname=='-') { - *tag1=0; - unary=TRUE; - ptr=fname; - } else { - *tag1=(int)strtol(fname,&ptr,16); - unary= ptr==fname; /* unary operator if it doesn't start with a tag name */ - } /* if */ - assert(!unary || *tag1==0); - assert(*ptr!='\0'); - for (name=opname; !isdigit(*ptr); ) - *name++ = *ptr++; - *name='\0'; - *tag2=(int)strtol(ptr,NULL,16); - return unary; -} - -constvalue *find_tag_byval(int tag) -{ - return find_constval_byval(&tagname_tab, tag); -} - -char *funcdisplayname(char *dest,char *funcname) -{ - int tags[2]; - char opname[10]; - constvalue *tagsym[2]; - int unary; - - if (isalpha(*funcname) || *funcname=='_' || *funcname==PUBLIC_CHAR || *funcname=='\0') { - if (dest!=funcname) - strcpy(dest,funcname); - return dest; - } /* if */ - - unary=parse_funcname(funcname,&tags[0],&tags[1],opname); - tagsym[1]=find_tag_byval(tags[1]); - assert(tagsym[1]!=NULL); - if (unary) { - sprintf(dest,"operator%s(%s:)",opname,tagsym[1]->name); - } else { - tagsym[0]=find_tag_byval(tags[0]); - assert(tagsym[0]!=NULL); - /* special case: the assignment operator has the return value as the 2nd tag */ - if (opname[0]=='=' && opname[1]=='\0') - sprintf(dest,"%s:operator%s(%s:)",tagsym[0]->name,opname,tagsym[1]->name); - else - sprintf(dest,"operator%s(%s:,%s:)",opname,tagsym[0]->name,tagsym[1]->name); - } /* if */ - return dest; -} - -static cell char_array_cells(cell size) -{ - return (size + sizeof(cell) - 1) / sizeof(cell); -} - -static cell fix_char_size(declinfo_t *decl) -{ - typeinfo_t *type = &decl->type; - if (type->tag == pc_tag_string && type->numdim && type->dim[type->numdim - 1]) { - cell slength = type->dim[type->numdim - 1]; - type->dim[type->numdim - 1] = char_array_cells(type->size); - return slength; - } - return 0; -} - -static symbol *funcstub(int tokid, declinfo_t *decl, const int *thistag) -{ - char *str; - cell val; - symbol *sym; - int fnative = (tokid == tNATIVE || tokid == tMETHODMAP); - int fpublic = (tokid == tPUBLIC); - - lastst=0; - litidx=0; /* clear the literal pool */ - assert(loctab.next==NULL); /* local symbol table should be empty */ - - fix_char_size(decl); - - if (decl->opertok) - check_operatortag(decl->opertok, decl->type.tag, decl->name); - - needtoken('('); /* only functions may be native/forward */ - - sym=fetchfunc(decl->name); - if (sym==NULL) - return NULL; - if ((sym->usage & uPROTOTYPED)!=0 && !compare_tag(sym->tag, decl->type.tag)) - error(25); - if ((sym->usage & uDEFINE) == 0) { - // As long as the function stays undefined, update its address and tag. - sym->addr = code_idx; - sym->tag = decl->type.tag; - } - - if (fnative) { - sym->usage=(char)(uNATIVE | uRETVALUE | uDEFINE | (sym->usage & uPROTOTYPED)); - sym->x.lib=curlibrary; - } else if (fpublic) { - sym->usage|=uPUBLIC; - } /* if */ - sym->usage|=uFORWARD; - - declargs(sym, FALSE, thistag); - /* "declargs()" found the ")" */ - sc_attachdocumentation(sym); /* attach any documenation to the function */ - if (!operatoradjust(decl->opertok,sym,decl->name,decl->type.tag)) - sym->usage &= ~uDEFINE; - - if (getstates(decl->name)!=0) { - if (fnative || decl->opertok!=0) - error(82); /* native functions and operators may not have states */ - else - error(231); /* ignoring state specifications on forward declarations */ - } /* if */ - - /* for a native operator, also need to specify an "exported" function name; - * for a native function, this is optional - */ - if (fnative) { - if (decl->opertok!=0) { - needtoken('='); - lexpush(); /* push back, for matchtoken() to retrieve again */ - } /* if */ - if (matchtoken('=')) { - /* allow number or symbol */ - if (matchtoken(tSYMBOL)) { - tokeninfo(&val,&str); - insert_alias(sym->name,str); - } else { - exprconst(&val,NULL,NULL); - sym->addr=val; - /* At the moment, I have assumed that this syntax is only valid if - * val < 0. To properly mix "normal" native functions and indexed - * native functions, one should use negative indices anyway. - * Special code for a negative index in sym->addr exists in SC4.C - * (ffcall()) and in SC6.C (the loops for counting the number of native - * variables and for writing them). - */ - } /* if */ - } /* if */ - } /* if */ - - // Don't look for line endings if we're inline. - if (tokid != tMETHODMAP) - needtoken(tTERM); - - /* attach the array to the function symbol */ - if (decl->type.numdim>0) - error(141); - - litidx=0; /* clear the literal pool */ - delete_symbols(&loctab,0,TRUE,TRUE);/* clear local variables queue */ - - return sym; -} - -/* newfunc - begin a function - * - * This routine is called from "parse" and tries to make a function - * out of the following text - * - * Global references: funcstatus,lastst,litidx - * rettype (altered) - * curfunc (altered) - * declared (altered) - * glb_declared (altered) - * sc_alignnext (altered) - */ -static int newfunc(declinfo_t *decl, const int *thistag, int fpublic, int fstatic, int stock, symbol **symp) -{ - symbol *sym; - int argcnt,funcline; - int opererror; - cell cidx,glbdecl; - short filenum; - - assert(litidx==0); /* literal queue should be empty */ - litidx=0; /* clear the literal pool (should already be empty) */ - lastst=0; /* no statement yet */ - cidx=0; /* just to avoid compiler warnings */ - glbdecl=0; - assert(loctab.next==NULL); /* local symbol table should be empty */ - filenum=fcurrent; /* save file number at the start of the declaration */ - - if (symp) - *symp = NULL; - - check_void_decl(decl, FALSE); - - if (decl->opertok) { - check_operatortag(decl->opertok, decl->type.tag, decl->name); - } /* if */ - - /* check whether this is a function or a variable declaration */ - if (!matchtoken('(')) - return FALSE; - /* so it is a function, proceed */ - funcline=fline; /* save line at which the function is defined */ - if (decl->name[0]==PUBLIC_CHAR) { - fpublic=TRUE; /* implicitly public function */ - if (stock) - error(42); /* invalid combination of class specifiers */ - } /* if */ - - if ((sym=fetchfunc(decl->name)) == NULL) - return TRUE; - - // Not a valid function declaration if native. - if (sym->usage & uNATIVE) - return TRUE; - - // If the function has not been prototyed, set its tag. - if (!(sym->usage & uPROTOTYPED)) - sym->tag = decl->type.tag; - - // As long as the function stays undefined, update its address. - if (!(sym->usage & uDEFINE)) - sym->addr = code_idx; - - if (fpublic) - sym->usage|=uPUBLIC; - if (fstatic) - sym->fnumber=filenum; - - if (sym->usage & (uPUBLIC | uFORWARD)) { - if (decl->type.numdim > 0) - error(141); - } - - /* if the function was used before being declared, and it has a tag for the - * result, add a third pass (as second "skimming" parse) because the function - * result may have been used with user-defined operators, which have now - * been incorrectly flagged (as the return tag was unknown at the time of - * the call) - */ - if ((sym->usage & (uPROTOTYPED | uREAD))==uREAD && sym->tag!=0) { - int curstatus=sc_status; - sc_status=statWRITE; /* temporarily set status to WRITE, so the warning isn't blocked */ -#if 0 /* SourceMod - silly, should be removed in first pass, so removed */ - error(208); -#endif - sc_status=curstatus; - sc_reparse=TRUE; /* must add another pass to "initial scan" phase */ - } /* if */ - - /* declare all arguments */ - argcnt = declargs(sym, TRUE, thistag); - opererror = !operatoradjust(decl->opertok, sym, decl->name, decl->type.tag); - if (strcmp(decl->name, uMAINFUNC)==0 || strcmp(decl->name, uENTRYFUNC)==0) { - if (argcnt>0) - error(5); /* "main()" and "entry()" functions may not have any arguments */ - sym->usage|=uREAD; /* "main()" is the program's entry point: always used */ - } /* if */ - - if ((sym->usage & uDEFINE)!=0) - error(21, sym->name); - - /* "declargs()" found the ")"; if a ";" appears after this, it was a - * prototype */ - if (matchtoken(';')) { - if (sym->usage & uPUBLIC) - error(10); - sym->usage|=uFORWARD; - if (!sc_needsemicolon) - error(10); /* old style prototypes used with optional semicolumns */ - delete_symbols(&loctab,0,TRUE,TRUE); /* prototype is done; forget everything */ - return TRUE; - } /* if */ - /* so it is not a prototype, proceed */ - - /* if this is a function that is not referred to (this can only be detected - * in the second stage), shut code generation off */ - if (sc_status==statWRITE && (sym->usage & uREAD)==0 && !fpublic) { - cidx=code_idx; - glbdecl=glb_declared; - - sc_status=statSKIP; - - // If this is a method, output errors even if it's unused. - if (thistag && *thistag != -1) - sc_err_status = TRUE; - } /* if */ - - if ((sym->flags & flgDEPRECATED) != 0 && (sym->usage & uSTOCK) == 0) { - const char *ptr= (sym->documentation!=NULL) ? sym->documentation : ""; - error(234, decl->name, ptr); /* deprecated (probably a public function) */ - } /* if */ - begcseg(); - sym->usage|=uDEFINE; /* set the definition flag */ - if (stock) - sym->usage|=uSTOCK; - if (decl->opertok != 0 && opererror) - sym->usage &= ~uDEFINE; - startfunc(sym->name); /* creates stack frame */ - insert_dbgline(funcline); - setline(FALSE); - if (sc_alignnext) { - alignframe(sc_dataalign); - sc_alignnext=FALSE; - } /* if */ - declared=0; /* number of local cells */ - resetstacklist(); - resetheaplist(); - rettype=(sym->usage & uRETVALUE); /* set "return type" variable */ - curfunc=sym; - define_args(); /* add the symbolic info for the function arguments */ - #if !defined SC_LIGHT - if (matchtoken('{')) { - lexpush(); - } else { - // We require '{' for new methods. - if (decl->type.is_new) - needtoken('{'); - - /* Insert a separator so that comments following the statement will not - * be attached to this function; they should be attached to the next - * function. This is not a problem for functions having a compound block, - * because the closing brace is an explicit "end token" for the function. - * With single statement functions, the preprocessor may overread the - * source code before the parser determines an "end of statement". - */ - insert_docstring_separator(); - } /* if */ - #endif - statement(NULL,FALSE); - - if ((rettype & uRETVALUE)!=0) { - sym->usage|=uRETVALUE; - } else { - if (sym->tag == pc_tag_void && - (sym->usage & uFORWARD) && - !decl->type.tag && - !decl->type.is_new) - { - // We got something like: - // forward void X(); - // public X() - // - // Switch our decl type to void. - decl->type.tag = pc_tag_void; - decl->type.tags[0] = pc_tag_void; - } - } - - // Check that return tags match. - if ((sym->usage & uPROTOTYPED) && !compare_tag(sym->tag, decl->type.tag)) { - int old_fline = fline; - fline = funcline; - error(180, type_to_name(sym->tag), type_to_name(decl->type.tag)); - fline = old_fline; - } - - if (declared!=0) { - /* This happens only in a very special (and useless) case, where a function - * has only a single statement in its body (no compound block) and that - * statement declares a new variable - */ - popstacklist(1); - declared=0; - } /* if */ - if ((lastst!=tRETURN) && (lastst!=tGOTO)){ - ldconst(0,sPRI); - ffret(strcmp(sym->name,uENTRYFUNC)!=0); - if ((sym->usage & uRETVALUE)!=0) { - char symname[2*sNAMEMAX+16]; /* allow space for user defined operators */ - funcdisplayname(symname,sym->name); - error(209,symname); /* function should return a value */ - } /* if */ - } /* if */ - endfunc(); - sym->codeaddr=code_idx; - sc_attachdocumentation(sym); /* attach collected documenation to the function */ - if (litidx) { /* if there are literals defined */ - glb_declared+=litidx; - begdseg(); /* flip to DATA segment */ - dumplits(); /* dump literal strings */ - litidx=0; - } /* if */ - testsymbols(&loctab,0,TRUE,TRUE); /* test for unused arguments and labels */ - delete_symbols(&loctab,0,TRUE,TRUE); /* clear local variables queue */ - assert(loctab.next==NULL); - curfunc=NULL; - if (sc_status==statSKIP) { - sc_status=statWRITE; - code_idx=cidx; - glb_declared=glbdecl; - sc_err_status=FALSE; - } /* if */ - if (symp) - *symp = sym; - return TRUE; -} - -static int argcompare(arginfo *a1,arginfo *a2) -{ - int result,level,i; - - result=1; - if (result) - result= a1->ident==a2->ident; /* type/class */ - if (result) - result= a1->usage==a2->usage; /* "const" flag */ - if (result) - result= a1->numtags==a2->numtags; /* tags (number and names) */ - for (i=0; result && inumtags; i++) - result= compare_tag(a1->tags[i], a2->tags[i]); - if (result) - result= a1->numdim==a2->numdim; /* array dimensions & index tags */ - for (level=0; result && levelnumdim; level++) - result= a1->dim[level]==a2->dim[level]; - for (level=0; result && levelnumdim; level++) - result= compare_tag(a1->idxtag[level], a2->idxtag[level]); - if (result) - result= a1->hasdefault==a2->hasdefault; /* availability of default value */ - if (a1->hasdefault) { - if (a1->ident==iREFARRAY) { - if (result) - result= a1->defvalue.array.size==a2->defvalue.array.size; - if (result) - result= a1->defvalue.array.arraysize==a2->defvalue.array.arraysize; - /* ??? should also check contents of the default array (these troubles - * go away in a 2-pass compiler that forbids double declarations, but - * Pawn currently does not forbid them) */ - } else { - if (result) { - result= a1->defvalue.val==a2->defvalue.val; - } /* if */ - } /* if */ - if (result) - result= compare_tag(a1->defvalue_tag, a2->defvalue_tag); - } /* if */ - return result; -} - -/* declargs() - * - * This routine adds an entry in the local symbol table for each argument - * found in the argument list. It returns the number of arguments. - */ -static int declargs(symbol *sym, int chkshadow, const int *thistag) -{ - char *ptr; - int argcnt,oldargcnt; - arginfo arg, *arglist; - char name[sNAMEMAX+1]; - int fpublic; - int idx; - - /* if the function is already defined earlier, get the number of arguments - * of the existing definition - */ - oldargcnt=0; - if ((sym->usage & uPROTOTYPED)!=0) - while (sym->dim.arglist[oldargcnt].ident!=0) - oldargcnt++; - argcnt=0; /* zero aruments up to now */ - fpublic = (sym->usage & (uPUBLIC|uSTOCK))!=0; - - if (thistag && *thistag != -1) { - arginfo *argptr; - if ((sym->usage & uPROTOTYPED) == 0) { - // Allocate space for a new argument, then terminate. - sym->dim.arglist = (arginfo *)realloc(sym->dim.arglist, (argcnt + 2) * sizeof(arginfo)); - memset(&sym->dim.arglist[argcnt + 1], 0, sizeof(arginfo)); - - argptr = &sym->dim.arglist[argcnt]; - memset(argptr, 0, sizeof(*argptr)); - strcpy(argptr->name, "this"); - argptr->ident = iVARIABLE; - argptr->tags = (int *)malloc(sizeof(int)); - argptr->tags[0] = *thistag; - argptr->numtags = 1; - argptr->usage = uCONST; - } else { - argptr = &sym->dim.arglist[0]; - } - - symbol *sym = addvariable2( - argptr->name, - (argcnt+3)*sizeof(cell), - argptr->ident, - sLOCAL, - argptr->tags[0], - argptr->dim, - argptr->numdim, - argptr->idxtag, - 0 - ); - sym->usage |= uCONST; - markusage(sym, uREAD); - - argcnt++; - } - - /* the '(' parantheses has already been parsed */ - if (!matchtoken(')')){ - do { /* there are arguments; process them */ - declinfo_t decl; - - parse_decl(&decl, DECLFLAG_ARGUMENT|DECLFLAG_ENUMROOT); - assert(decl.type.numtags > 0); - - check_void_decl(&decl, TRUE); - - if (decl.type.ident == iVARARGS) { - assert(decl.type.numtags > 0); - if ((sym->usage & uPROTOTYPED)==0) { - /* redimension the argument list, add the entry iVARARGS */ - sym->dim.arglist=(arginfo*)realloc(sym->dim.arglist,(argcnt+2)*sizeof(arginfo)); - if (sym->dim.arglist==0) - error(FATAL_ERROR_OOM); /* insufficient memory */ - memset(&sym->dim.arglist[argcnt+1],0,sizeof(arginfo)); /* keep the list terminated */ - sym->dim.arglist[argcnt].ident=iVARARGS; - sym->dim.arglist[argcnt].hasdefault=FALSE; - sym->dim.arglist[argcnt].defvalue.val=0; - sym->dim.arglist[argcnt].defvalue_tag=0; - sym->dim.arglist[argcnt].numtags=decl.type.numtags; - sym->dim.arglist[argcnt].tags=(int*)malloc(decl.type.numtags*sizeof decl.type.tags[0]); - if (sym->dim.arglist[argcnt].tags==NULL) - error(FATAL_ERROR_OOM); /* insufficient memory */ - memcpy(sym->dim.arglist[argcnt].tags,decl.type.tags,decl.type.numtags*sizeof decl.type.tags[0]); - } else { - if (argcnt>oldargcnt || sym->dim.arglist[argcnt].ident!=iVARARGS) - error(25); /* function definition does not match prototype */ - } /* if */ - argcnt++; - continue; - } - - if (argcnt>=sMAXARGS) - error(45); - if (decl.name[0] == PUBLIC_CHAR) - error(56, decl.name); /* function arguments cannot be public */ - - if (decl.type.ident == iARRAY) - decl.type.ident = iREFARRAY; - /* Stack layout: - * base + 0*sizeof(cell) == previous "base" - * base + 1*sizeof(cell) == function return address - * base + 2*sizeof(cell) == number of arguments - * base + 3*sizeof(cell) == first argument of the function - * So the offset of each argument is "(argcnt+3) * sizeof(cell)". - */ - doarg(&decl,(argcnt+3)*sizeof(cell),fpublic,chkshadow,&arg); - - if ((sym->usage & uPUBLIC) && arg.hasdefault) - error(59, decl.name); /* arguments of a public function may not have a default value */ - - if ((sym->usage & uPROTOTYPED)==0) { - /* redimension the argument list, add the entry */ - sym->dim.arglist=(arginfo*)realloc(sym->dim.arglist,(argcnt+2)*sizeof(arginfo)); - if (sym->dim.arglist==0) - error(FATAL_ERROR_OOM); /* insufficient memory */ - memset(&sym->dim.arglist[argcnt+1],0,sizeof(arginfo)); /* keep the list terminated */ - sym->dim.arglist[argcnt]=arg; - } else { - /* check the argument with the earlier definition */ - if (argcnt>oldargcnt || !argcompare(&sym->dim.arglist[argcnt],&arg)) - error(181, arg.name); /* function argument does not match prototype */ - /* may need to free default array argument and the tag list */ - if (arg.ident==iREFARRAY && arg.hasdefault) - free(arg.defvalue.array.data); - free(arg.tags); - } /* if */ - argcnt++; - } while (matchtoken(',')); - /* if the next token is not ",", it should be ")" */ - needtoken(')'); - } /* if */ - - sym->usage|=uPROTOTYPED; - errorset(sRESET,0); /* reset error flag (clear the "panic mode")*/ - return argcnt; -} - -/* doarg - declare one argument type - * - * this routine is called from "declargs()" and adds an entry in the local - * symbol table for one argument. - * - * "fpublic" indicates whether the function for this argument list is public. - * The arguments themselves are never public. - */ -static void doarg(declinfo_t *decl, int offset, int fpublic, int chkshadow, arginfo *arg) -{ - symbol *argsym; - int slength=0; - typeinfo_t *type = &decl->type; - - // Otherwise we get very weird line number ranges, anything to the current fline. - errorset(sEXPRMARK,0); - - strcpy(arg->name, decl->name); - arg->hasdefault=FALSE; /* preset (most common case) */ - arg->defvalue.val=0; /* clear */ - arg->defvalue_tag=0; - arg->numdim=0; - if (type->ident == iREFARRAY) { - arg->numdim = type->numdim; - memcpy(arg->dim, type->dim, sizeof(int) * type->numdim); - memcpy(arg->idxtag, type->idxtag, sizeof(int) * type->numdim); - assert(type->numtags > 0); - if (type->tags[0] == pc_tag_string) { - slength = arg->dim[arg->numdim - 1]; - arg->dim[arg->numdim - 1] = (type->size + sizeof(cell) - 1) / sizeof(cell); - } - if (matchtoken('=')) { - assert(litidx==0); /* at the start of a function, this is reset */ - /* Check if there is a symbol */ - if (matchtoken(tSYMBOL)) { - symbol *sym; - char *name; - cell val; - tokeninfo(&val,&name); - if ((sym=findglb(name, sGLOBAL)) == NULL) { - error(17, name); /* undefined symbol */ - } else { - arg->hasdefault=TRUE; /* argument as a default value */ - memset(&arg->defvalue, 0, sizeof(arg->defvalue)); - arg->defvalue.array.data=NULL; - arg->defvalue.array.addr=sym->addr; - arg->defvalue_tag=sym->tag; - if (sc_status==statWRITE && (sym->usage & uREAD)==0) { - markusage(sym, uREAD); - } - } - } else { - if (type->is_new && !type->has_postdims && lexpeek('{')) { - // Dynamic array with fixed initializer. - error(160); - } - initials2(type->ident, type->tags[0], &type->size, arg->dim, arg->numdim, type->enumroot, 1, 0); - assert(type->size >= litidx); - /* allocate memory to hold the initial values */ - arg->defvalue.array.data=(cell *)malloc(litidx*sizeof(cell)); - if (arg->defvalue.array.data!=NULL) { - int i; - memcpy(arg->defvalue.array.data,litq,litidx*sizeof(cell)); - arg->hasdefault=TRUE; /* argument has default value */ - arg->defvalue.array.size=litidx; - arg->defvalue.array.addr=-1; - /* calulate size to reserve on the heap */ - arg->defvalue.array.arraysize=1; - for (i=0; inumdim; i++) - arg->defvalue.array.arraysize*=arg->dim[i]; - if (arg->defvalue.array.arraysize < arg->defvalue.array.size) - arg->defvalue.array.arraysize = arg->defvalue.array.size; - } /* if */ - litidx=0; /* reset */ - } - } else { - if (type->is_new && type->has_postdims) { - for (int i = 0; i < type->numdim; i++) { - if (type->dim[i] <= 0) { - // Fixed-array with unknown size. - error(159); - break; - } - } - } - } - } else { - if (matchtoken('=')) { - unsigned char size_tag_token; - assert(type->ident==iVARIABLE || type->ident==iREFERENCE); - arg->hasdefault=TRUE; /* argument has a default value */ - exprconst(&arg->defvalue.val,&arg->defvalue_tag,NULL); - assert(type->numtags <= 1); - matchtag(type->tags[0], arg->defvalue_tag, TRUE); - } /* if */ - } /* if */ - arg->ident=(char)type->ident; - arg->usage=type->usage; - arg->numtags=type->numtags; - arg->tags=(int*)malloc(type->numtags * sizeof(type->tags[0])); - if (arg->tags==NULL) - error(FATAL_ERROR_OOM); /* insufficient memory */ - memcpy(arg->tags, type->tags, type->numtags * sizeof(type->tags[0])); - argsym=findloc(decl->name); - if (argsym!=NULL) { - error(21, decl->name); /* symbol already defined */ - } else { - if (chkshadow && (argsym=findglb(decl->name,sSTATEVAR))!=NULL && argsym->ident!=iFUNCTN) - error(219, decl->name); /* variable shadows another symbol */ - /* add details of type and address */ - assert(type->numtags > 0); - argsym=addvariable2(decl->name,offset,type->ident,sLOCAL,type->tags[0], - arg->dim,arg->numdim,arg->idxtag,slength); - argsym->compound=0; - if (type->ident==iREFERENCE) - argsym->usage|=uREAD; /* because references are passed back */ - if (fpublic) - argsym->usage|=uREAD; /* arguments of public functions are always "used" */ - if (type->usage & uCONST) - argsym->usage|=uCONST; - } /* if */ - - errorset(sEXPRRELEASE,0); -} - -static int count_referrers(symbol *entry) -{ - int i,count; - - count=0; - for (i=0; inumrefers; i++) - if (entry->refer[i]!=NULL) - count++; - return count; -} - -#if !defined SC_LIGHT -static int find_xmltag(char *source, const char *xmltag, const char *xmlparam, const char *xmlvalue, - char **outer_start,int *outer_length, - const char **inner_start,int *inner_length) -{ - char *ptr; - const char *inner_end; - int xmltag_len,xmlparam_len,xmlvalue_len; - int match; - - assert(source!=NULL); - assert(xmltag!=NULL); - assert(outer_start!=NULL); - assert(outer_length!=NULL); - assert(inner_start!=NULL); - assert(inner_length!=NULL); - - /* both NULL or both non-NULL */ - assert((xmlvalue!=NULL && xmlparam!=NULL) || (xmlvalue==NULL && xmlparam==NULL)); - - xmltag_len=strlen(xmltag); - xmlparam_len= (xmlparam!=NULL) ? strlen(xmlparam) : 0; - xmlvalue_len= (xmlvalue!=NULL) ? strlen(xmlvalue) : 0; - ptr=source; - /* find an opening '<' */ - while ((ptr=strchr(ptr,'<'))!=NULL) { - *outer_start=ptr; /* be optimistic... */ - match=FALSE; /* ...and pessimistic at the same time */ - ptr++; /* skip '<' */ - while (*ptr!='\0' && *ptr<=' ') - ptr++; /* skip white space */ - if (strncmp(ptr,xmltag,xmltag_len)==0 && (*(ptr+xmltag_len)<=' ' || *(ptr+xmltag_len)=='>')) { - /* xml tag found, optionally check the parameter */ - ptr+=xmltag_len; - while (*ptr!='\0' && *ptr<=' ') - ptr++; /* skip white space */ - if (xmlparam!=NULL) { - if (strncmp(ptr,xmlparam,xmlparam_len)==0 && (*(ptr+xmlparam_len)<=' ' || *(ptr+xmlparam_len)=='=')) { - ptr+=xmlparam_len; - while (*ptr!='\0' && *ptr<=' ') - ptr++; /* skip white space */ - if (*ptr=='=') { - ptr++; /* skip '=' */ - while (*ptr!='\0' && *ptr<=' ') - ptr++; /* skip white space */ - if (*ptr=='"' || *ptr=='\'') - ptr++; /* skip " or ' */ - assert(xmlvalue!=NULL); - if (strncmp(ptr,xmlvalue,xmlvalue_len)==0 - && (*(ptr+xmlvalue_len)<=' ' - || *(ptr+xmlvalue_len)=='>' - || *(ptr+xmlvalue_len)=='"' - || *(ptr+xmlvalue_len)=='\'')) - match=TRUE; /* found it */ - } /* if */ - } /* if */ - } else { - match=TRUE; /* don't check the parameter */ - } /* if */ - } /* if */ - if (match) { - /* now find the end of the opening tag */ - while (*ptr!='\0' && *ptr!='>') - ptr++; - if (*ptr=='>') - ptr++; - while (*ptr!='\0' && *ptr<=' ') - ptr++; /* skip white space */ - *inner_start=ptr; - /* find the start of the closing tag (assume no nesting) */ - while ((ptr=strchr(ptr,'<'))!=NULL) { - inner_end=ptr; - ptr++; /* skip '<' */ - while (*ptr!='\0' && *ptr<=' ') - ptr++; /* skip white space */ - if (*ptr=='/') { - ptr++; /* skip / */ - while (*ptr!='\0' && *ptr<=' ') - ptr++; /* skip white space */ - if (strncmp(ptr,xmltag,xmltag_len)==0 && (*(ptr+xmltag_len)<=' ' || *(ptr+xmltag_len)=='>')) { - /* find the end of the closing tag */ - while (*ptr!='\0' && *ptr!='>') - ptr++; - if (*ptr=='>') - ptr++; - /* set the lengths of the inner and outer segment */ - assert(*inner_start!=NULL); - *inner_length=(int)(inner_end-*inner_start); - assert(*outer_start!=NULL); - *outer_length=(int)(ptr-*outer_start); - break; /* break out of the loop */ - } /* if */ - } /* if */ - } /* while */ - return TRUE; - } /* if */ - } /* while */ - return FALSE; /* not found */ -} - -static char *xmlencode(char *dest,char *source) -{ - char temp[2*sNAMEMAX+20],*ptr; - - /* replace < by < and such; normally, such a symbol occurs at most once in - * a symbol name (e.g. "operator<") - */ - ptr=temp; - while (*source!='\0') { - switch (*source) { - case '<': - strcpy(ptr,"<"); - ptr+=4; - break; - case '>': - strcpy(ptr,">"); - ptr+=4; - break; - case '&': - strcpy(ptr,"&"); - ptr+=5; - break; - default: - *ptr++=*source; - } /* switch */ - source++; - } /* while */ - *ptr='\0'; - strcpy(dest,temp); - return dest; -} - -static void make_report(symbol *root,FILE *log,char *sourcefile) -{ - char symname[_MAX_PATH]; - int i,arg; - symbol *sym,*ref; - constvalue *tagsym; - constvalue *enumroot; - char *ptr; - - /* adapt the installation directory */ - strcpy(symname,sc_rootpath); - #if DIRSEP_CHAR=='\\' - while ((ptr=strchr(symname,':'))!=NULL) - *ptr='|'; - while ((ptr=strchr(symname,DIRSEP_CHAR))!=NULL) - *ptr='/'; - #endif - - /* the XML header */ - fprintf(log,"\n"); - fprintf(log,"\n",symname); - fprintf(log,"\n",sourcefile); - ptr=strrchr(sourcefile,DIRSEP_CHAR); - if (ptr!=NULL) - ptr++; - else - ptr=sourcefile; - fprintf(log,"\t\n\t\t%s\n\t\n",ptr); - - /* attach the global documentation, if any */ - if (sc_documentation!=NULL) { - fprintf(log,"\n\t\n"); - fprintf(log,"\t\n\t\t"); - fputs(sc_documentation,log); - fprintf(log,"\n\t\n\n"); - } /* if */ - - /* use multiple passes to print constants variables and functions in - * separate sections - */ - fprintf(log,"\t\n"); - - fprintf(log,"\n\t\t\n"); - for (sym=root->next; sym!=NULL; sym=sym->next) { - if (sym->parent!=NULL) - continue; /* hierarchical data type */ - assert(sym->ident==iCONSTEXPR || sym->ident==iVARIABLE - || sym->ident==iARRAY || sym->ident==iFUNCTN); - if (sym->ident!=iCONSTEXPR || (sym->usage & uENUMROOT)==0) - continue; - if ((sym->usage & uREAD)==0) - continue; - fprintf(log,"\t\t\n",funcdisplayname(symname,sym->name),sym->addr); - if (sym->tag!=0) { - tagsym=find_tag_byval(sym->tag); - assert(tagsym!=NULL); - fprintf(log,"\t\t\t\n",tagsym->name); - } /* if */ - /* browse through all fields */ - if ((enumroot=sym->dim.enumlist)!=NULL) { - enumroot=enumroot->next; /* skip root */ - while (enumroot!=NULL) { - fprintf(log,"\t\t\t\n",funcdisplayname(symname,enumroot->name),enumroot->value); - /* find the constant with this name and get the tag */ - ref=findglb(enumroot->name,sGLOBAL); - if (ref!=NULL) { - if (ref->x.tags.index!=0) { - tagsym=find_tag_byval(ref->x.tags.index); - assert(tagsym!=NULL); - fprintf(log,"\t\t\t\t\n",tagsym->name); - } /* if */ - if (ref->dim.array.length!=1) - fprintf(log,"\t\t\t\t\n",(long)ref->dim.array.length); - } /* if */ - fprintf(log,"\t\t\t\n"); - enumroot=enumroot->next; - } /* while */ - } /* if */ - assert(sym->refer!=NULL); - for (i=0; inumrefers; i++) { - if ((ref=sym->refer[i])!=NULL) - fprintf(log,"\t\t\t\n",xmlencode(symname,funcdisplayname(symname,ref->name))); - } /* for */ - if (sym->documentation!=NULL) - fprintf(log,"\t\t\t%s\n",sym->documentation); - fprintf(log,"\t\t\n"); - } /* for */ - - fprintf(log,"\n\t\t\n"); - for (sym=root->next; sym!=NULL; sym=sym->next) { - if (sym->parent!=NULL) - continue; /* hierarchical data type */ - assert(sym->ident==iCONSTEXPR || sym->ident==iVARIABLE - || sym->ident==iARRAY || sym->ident==iFUNCTN); - if (sym->ident!=iCONSTEXPR) - continue; - if ((sym->usage & uREAD)==0 || (sym->usage & (uENUMFIELD | uENUMROOT))!=0) - continue; - fprintf(log,"\t\t\n",funcdisplayname(symname,sym->name),sym->addr); - if (sym->tag!=0) { - tagsym=find_tag_byval(sym->tag); - assert(tagsym!=NULL); - fprintf(log,"\t\t\t\n",tagsym->name); - } /* if */ - assert(sym->refer!=NULL); - for (i=0; inumrefers; i++) { - if ((ref=sym->refer[i])!=NULL) - fprintf(log,"\t\t\t\n",xmlencode(symname,funcdisplayname(symname,ref->name))); - } /* for */ - if (sym->documentation!=NULL) - fprintf(log,"\t\t\t%s\n",sym->documentation); - fprintf(log,"\t\t\n"); - } /* for */ - - fprintf(log,"\n\t\t\n"); - for (sym=root->next; sym!=NULL; sym=sym->next) { - if (sym->parent!=NULL) - continue; /* hierarchical data type */ - if (sym->ident!=iVARIABLE && sym->ident!=iARRAY) - continue; - fprintf(log,"\t\t\n",funcdisplayname(symname,sym->name)); - if (sym->tag!=0) { - tagsym=find_tag_byval(sym->tag); - assert(tagsym!=NULL); - fprintf(log,"\t\t\t\n",tagsym->name); - } /* if */ - assert(sym->refer!=NULL); - if ((sym->usage & uPUBLIC)!=0) - fprintf(log,"\t\t\t\n"); - for (i=0; inumrefers; i++) { - if ((ref=sym->refer[i])!=NULL) - fprintf(log,"\t\t\t\n",xmlencode(symname,funcdisplayname(symname,ref->name))); - } /* for */ - if (sym->documentation!=NULL) - fprintf(log,"\t\t\t%s\n",sym->documentation); - fprintf(log,"\t\t\n"); - } /* for */ - - fprintf(log,"\n\t\t\n"); - for (sym=root->next; sym!=NULL; sym=sym->next) { - if (sym->parent!=NULL) - continue; /* hierarchical data type */ - if (sym->ident!=iFUNCTN) - continue; - if ((sym->usage & (uREAD | uNATIVE))==uNATIVE) - continue; /* unused native function */ - funcdisplayname(symname,sym->name); - xmlencode(symname,symname); - fprintf(log,"\t\tdim.arglist!=NULL); - for (arg=0; sym->dim.arglist[arg].ident!=0; arg++) { - int dim; - if (arg>0) - fprintf(log,", "); - switch (sym->dim.arglist[arg].ident) { - case iVARIABLE: - fprintf(log,"%s",sym->dim.arglist[arg].name); - break; - case iREFERENCE: - fprintf(log,"&%s",sym->dim.arglist[arg].name); - break; - case iREFARRAY: - fprintf(log,"%s",sym->dim.arglist[arg].name); - for (dim=0; dimdim.arglist[arg].numdim;dim++) - fprintf(log,"[]"); - break; - case iVARARGS: - fprintf(log,"..."); - break; - } /* switch */ - } /* for */ - /* ??? should also print an "array return" size */ - fprintf(log,")\">\n"); - if (sym->tag!=0) { - tagsym=find_tag_byval(sym->tag); - assert(tagsym!=NULL); - fprintf(log,"\t\t\t\n",tagsym->name); - } /* if */ - /* check whether this function is called from the outside */ - if ((sym->usage & uNATIVE)!=0) - fprintf(log,"\t\t\t\n"); - if ((sym->usage & uPUBLIC)!=0) - fprintf(log,"\t\t\t\n"); - if (strcmp(sym->name,uMAINFUNC)==0 || strcmp(sym->name,uENTRYFUNC)==0) - fprintf(log,"\t\t\t\n"); - if ((sym->usage & uNATIVE)==0) - fprintf(log,"\t\t\t\n",(long)sym->x.stacksize); - if (sym->states!=NULL) { - constvalue *stlist=sym->states->next; - assert(stlist!=NULL); /* there should be at least one state item */ - while (stlist!=NULL && stlist->index==-1) - stlist=stlist->next; - assert(stlist!=NULL); /* state id should be found */ - i=state_getfsa(stlist->index); - assert(i>=0); /* automaton 0 exists */ - stlist=automaton_findid(i); - assert(stlist!=NULL); /* automaton should be found */ - fprintf(log,"\t\t\t\n", strlen(stlist->name)>0 ? stlist->name : "(anonymous)"); - //??? dump state decision table - } /* if */ - assert(sym->refer!=NULL); - for (i=0; inumrefers; i++) - if ((ref=sym->refer[i])!=NULL) - fprintf(log,"\t\t\t\n",xmlencode(symname,funcdisplayname(symname,ref->name))); - /* print all symbols that are required for this function to compile */ - for (ref=root->next; ref!=NULL; ref=ref->next) { - if (ref==sym) - continue; - for (i=0; inumrefers; i++) - if (ref->refer[i]==sym) - fprintf(log,"\t\t\t\n",xmlencode(symname,funcdisplayname(symname,ref->name))); - } /* for */ - /* print parameter list, with tag & const information, plus descriptions */ - assert(sym->dim.arglist!=NULL); - for (arg=0; sym->dim.arglist[arg].ident!=0; arg++) { - int dim,paraminfo; - char *outer_start; - const char *inner_start; - int outer_length,inner_length; - if (sym->dim.arglist[arg].ident==iVARARGS) - fprintf(log,"\t\t\t\n"); - else - fprintf(log,"\t\t\t\n",sym->dim.arglist[arg].name); - /* print the tag name(s) for each parameter */ - assert(sym->dim.arglist[arg].numtags>0); - assert(sym->dim.arglist[arg].tags!=NULL); - paraminfo=(sym->dim.arglist[arg].numtags>1 || sym->dim.arglist[arg].tags[0]!=0) - || sym->dim.arglist[arg].ident==iREFERENCE - || sym->dim.arglist[arg].ident==iREFARRAY; - if (paraminfo) - fprintf(log,"\t\t\t\t"); - if (sym->dim.arglist[arg].numtags>1 || sym->dim.arglist[arg].tags[0]!=0) { - assert(paraminfo); - if (sym->dim.arglist[arg].numtags>1) - fprintf(log," {"); - for (i=0; idim.arglist[arg].numtags; i++) { - if (i>0) - fprintf(log,","); - tagsym=find_tag_byval(sym->dim.arglist[arg].tags[i]); - assert(tagsym!=NULL); - fprintf(log,"%s",tagsym->name); - } /* for */ - if (sym->dim.arglist[arg].numtags>1) - fprintf(log,"}"); - } /* if */ - switch (sym->dim.arglist[arg].ident) { - case iREFERENCE: - fprintf(log," &"); - break; - case iREFARRAY: - fprintf(log," "); - for (dim=0; dimdim.arglist[arg].numdim; dim++) { - if (sym->dim.arglist[arg].dim[dim]==0) { - fprintf(log,"[]"); - } else { - //??? find index tag - fprintf(log,"[%d]",sym->dim.arglist[arg].dim[dim]); - } /* if */ - } /* for */ - break; - } /* switch */ - if (paraminfo) - fprintf(log," \n"); - /* print the user description of the parameter (parse through - * sym->documentation) - */ - if (sym->documentation!=NULL - && find_xmltag(sym->documentation, "param", "name", sym->dim.arglist[arg].name, - &outer_start, &outer_length, &inner_start, &inner_length)) - { - fprintf(log,"\t\t\t\t%.*s\n",inner_length,inner_start); - /* delete from documentation string */ - char *tail=outer_start+outer_length; - memmove(outer_start,tail,strlen(tail)+1); - } /* if */ - fprintf(log,"\t\t\t\n"); - } /* for */ - if (sym->documentation!=NULL) - fprintf(log,"\t\t\t%s\n",sym->documentation); - fprintf(log,"\t\t\n"); - } /* for */ - - fprintf(log,"\n\t\n"); - fprintf(log,"\n"); -} -#endif - -/* Every symbol has a referrer list, that contains the functions that use - * the symbol. Now, if function "apple" is accessed by functions "banana" and - * "citron", but neither function "banana" nor "citron" are used by anyone - * else, then, by inference, function "apple" is not used either. - */ -static void reduce_referrers(symbol *root) -{ - int i,restart; - symbol *sym,*ref; - - do { - restart=0; - for (sym=root->next; sym!=NULL; sym=sym->next) { - if (sym->parent!=NULL) - continue; /* hierarchical data type */ - if (sym->ident==iFUNCTN - && (sym->usage & uNATIVE)==0 - && (sym->usage & uPUBLIC)==0 && strcmp(sym->name,uMAINFUNC)!=0 && strcmp(sym->name,uENTRYFUNC)!=0 - && count_referrers(sym)==0) - { - sym->usage&=~(uREAD | uWRITTEN); /* erase usage bits if there is no referrer */ - /* find all symbols that are referred by this symbol */ - for (ref=root->next; ref!=NULL; ref=ref->next) { - if (ref->parent!=NULL) - continue; /* hierarchical data type */ - assert(ref->refer!=NULL); - for (i=0; inumrefers && ref->refer[i]!=sym; i++) - /* nothing */; - if (inumrefers) { - assert(ref->refer[i]==sym); - ref->refer[i]=NULL; - restart++; - } /* if */ - } /* for */ - } else if ((sym->ident==iVARIABLE || sym->ident==iARRAY) - && (sym->usage & uPUBLIC)==0 - && sym->parent==NULL - && count_referrers(sym)==0) - { - sym->usage&=~(uREAD | uWRITTEN); /* erase usage bits if there is no referrer */ - } /* if */ - } /* for */ - /* after removing a symbol, check whether more can be removed */ - } while (restart>0); -} - -#if !defined SC_LIGHT -static long max_stacksize_recurse(symbol *sourcesym,symbol *sym,long basesize,int *pubfuncparams,int *recursion) -{ - long size,maxsize; - int i; - - assert(sym!=NULL); - assert(sym->ident==iFUNCTN); - assert((sym->usage & uNATIVE)==0); - assert(recursion!=NULL); - - maxsize=sym->x.stacksize; - for (i=0; inumrefers; i++) { - if (sym->refer[i]!=NULL) { - assert(sym->refer[i]->ident==iFUNCTN); - assert((sym->refer[i]->usage & uNATIVE)==0); /* a native function cannot refer to a user-function */ - if (sym->refer[i]==sourcesym) { /* recursion detection */ - *recursion=1; - break; /* recursion was detected, quit loop */ - } /* if */ - size=max_stacksize_recurse(sourcesym,sym->refer[i],sym->x.stacksize,pubfuncparams,recursion); - if (maxsizeusage & uPUBLIC)!=0) { - /* Find out how many parameters a public function has, then see if this - * is bigger than some maximum - */ - arginfo *arg=sym->dim.arglist; - int count=0; - assert(arg!=0); - while (arg->ident!=0) { - count++; - arg++; - } /* while */ - assert(pubfuncparams!=0); - if (count>*pubfuncparams) - *pubfuncparams=count; - } /* if */ - - return maxsize+basesize; -} - -static symbol *save_symbol; - -static long max_stacksize(symbol *root,int *recursion) -{ - /* Loop over all non-native functions. For each function, loop - * over all of its referrers, accumulating the stack requirements. - * Detect (indirect) recursion with a "mark-and-sweep" algorithm. - * I (mis-)use the "compound" field of the symbol structure for - * the marker, as this field is unused for functions. - * - * Note that the stack is shared with the heap. A host application - * may "eat" cells from the heap as well, through amx_Allot(). The - * stack requirements are thus only an estimate. - */ - long size,maxsize; - int maxparams; - symbol *sym; - - assert(root!=NULL); - assert(recursion!=NULL); - #if !defined NDEBUG - for (sym=root->next; sym!=NULL; sym=sym->next) - if (sym->ident==iFUNCTN) - assert(sym->compound==0); - #endif - - maxsize=0; - maxparams=0; - *recursion=0; /* assume no recursion */ - for (sym=root->next; sym!=NULL; sym=sym->next) { - /* drop out if this is not a user-implemented function */ - if (sym->ident!=iFUNCTN || (sym->usage & uNATIVE)!=0) - continue; - /* accumulate stack size for this symbol */ - save_symbol = sym; - size=max_stacksize_recurse(sym,sym,0L,&maxparams,recursion); - assert(size>=0); - if (maxsizenext; - while (sym!=NULL && sym->compound>=level) { - switch (sym->ident) { - case iLABEL: - if (testlabs) { - if ((sym->usage & uDEFINE)==0) { - error(19,sym->name); /* not a label: ... */ - } else if ((sym->usage & uREAD)==0) { - errorset(sSETPOS,sym->lnumber); - error(203,sym->name); /* symbol isn't used: ... */ - } /* if */ - } /* if */ - break; - case iFUNCTN: - if ((sym->usage & (uDEFINE | uREAD | uNATIVE | uSTOCK | uPUBLIC))==uDEFINE) { - funcdisplayname(symname,sym->name); - if (strlen(symname)>0) - error(203,symname); /* symbol isn't used ... (and not public/native/stock) */ - } /* if */ - if ((sym->usage & uPUBLIC)!=0 || strcmp(sym->name,uMAINFUNC)==0) - entry=TRUE; /* there is an entry point */ - /* also mark the function to the debug information */ - if (((sym->usage & uREAD)!=0 || (sym->usage & uPUBLIC)!=0) && (sym->usage & uNATIVE)==0) - insert_dbgsymbol(sym); - break; - case iCONSTEXPR: - if (testconst && (sym->usage & uREAD)==0) { - errorset(sSETPOS,sym->lnumber); - error(203,sym->name); /* symbol isn't used: ... */ - } /* if */ - break; - case iMETHODMAP: - // Ignore usage on methodmaps. - break; - default: - /* a variable */ - if (sym->parent!=NULL) - break; /* hierarchical data type */ - if ((sym->usage & (uWRITTEN | uREAD | uSTOCK))==0) { - errorset(sSETPOS,sym->lnumber); - error(203,sym->name); /* symbol isn't used (and not stock) */ - } else if ((sym->usage & (uREAD | uSTOCK | uPUBLIC))==0) { - errorset(sSETPOS,sym->lnumber); - error(204,sym->name); /* value assigned to symbol is never used */ -#if 0 // ??? not sure whether it is a good idea to force people use "const" - } else if ((sym->usage & (uWRITTEN | uPUBLIC | uCONST))==0 && sym->ident==iREFARRAY) { - errorset(sSETPOS,sym->lnumber); - error(214,sym->name); /* make array argument "const" */ -#endif - } /* if */ - /* also mark the variable (local or global) to the debug information */ - if ((sym->usage & (uWRITTEN | uREAD))!=0 && (sym->usage & uNATIVE)==0) - insert_dbgsymbol(sym); - } /* if */ - sym=sym->next; - } /* while */ - - return entry; -} - -static cell calc_array_datasize(symbol *sym, cell *offset) -{ - cell length; - - assert(sym!=NULL); - assert(sym->ident==iARRAY || sym->ident==iREFARRAY); - length=sym->dim.array.length; - if (sym->dim.array.level > 0) { - cell sublength=calc_array_datasize(finddepend(sym),offset); - if (offset!=NULL) - *offset=length*(*offset+sizeof(cell)); - if (sublength>0) - length*=length*sublength; - else - length=0; - } else { - if (offset!=NULL) - *offset=0; - } /* if */ - return length; -} - -static void destructsymbols(symbol *root,int level) -{ - cell offset=0; - int savepri=FALSE; - symbol *sym=root->next; - while (sym!=NULL && get_actual_compound(sym)>=level) { - if (sym->ident==iVARIABLE || sym->ident==iARRAY) { - char symbolname[16]; - symbol *opsym; - cell elements; - /* check that the '~' operator is defined for this tag */ - operator_symname(symbolname,"~",sym->tag,0,1,0); - if ((opsym=findglb(symbolname,sGLOBAL))!=NULL) { - /* save PRI, in case of a return statment */ - if (!savepri) { - pushreg(sPRI); /* right-hand operand is in PRI */ - savepri=TRUE; - } /* if */ - /* if the variable is an array, get the number of elements */ - if (sym->ident==iARRAY) { - elements=calc_array_datasize(sym,&offset); - /* "elements" can be zero when the variable is declared like - * new mytag: myvar[2][] = { {1, 2}, {3, 4} } - * one should declare all dimensions! - */ - if (elements==0) - error(46,sym->name); /* array size is unknown */ - } else { - elements=1; - offset=0; - } /* if */ - pushval(elements); - /* call the '~' operator */ - address(sym,sPRI); - addconst(offset); /* add offset to array data to the address */ - pushreg(sPRI); - pushval(2 /* *sizeof(cell)*/ );/* 2 parameters */ - assert(opsym->ident==iFUNCTN); - ffcall(opsym,NULL,1); - if (sc_status!=statSKIP) - markusage(opsym,uREAD); /* do not mark as "used" when this call itself is skipped */ - if ((opsym->usage & uNATIVE)!=0 && opsym->x.lib!=NULL) - opsym->x.lib->value += 1; /* increment "usage count" of the library */ - } /* if */ - } /* if */ - sym=sym->next; - } /* while */ - /* restore PRI, if it was saved */ - if (savepri) - popreg(sPRI); -} - -static constvalue *insert_constval(constvalue *prev,constvalue *next,const char *name,cell val, - int index) -{ - constvalue *cur; - - if ((cur=(constvalue*)malloc(sizeof(constvalue)))==NULL) - error(FATAL_ERROR_OOM); /* insufficient memory (fatal error) */ - memset(cur,0,sizeof(constvalue)); - if (name!=NULL) { - assert(strlen(name)<=sNAMEMAX); - strcpy(cur->name,name); - } /* if */ - cur->value=val; - cur->index=index; - cur->next=next; - prev->next=cur; - return cur; -} - -constvalue *append_constval(constvalue *table,const char *name,cell val,int index) -{ - constvalue *cur,*prev; - - /* find the end of the constant table */ - for (prev=table, cur=table->next; cur!=NULL; prev=cur, cur=cur->next) - /* nothing */; - return insert_constval(prev,NULL,name,val,index); -} - -constvalue *find_constval(constvalue *table,char *name,int index) -{ - constvalue *ptr = table->next; - - while (ptr!=NULL) { - if (strcmp(name,ptr->name)==0 && ptr->index==index) - return ptr; - ptr=ptr->next; - } /* while */ - return NULL; -} - -static constvalue *find_constval_byval(constvalue *table,cell val) -{ - constvalue *ptr = table->next; - - while (ptr!=NULL) { - if (ptr->value==val) - return ptr; - ptr=ptr->next; - } /* while */ - return NULL; -} - -#if 0 /* never used */ -static int delete_constval(constvalue *table,char *name) -{ - constvalue *prev = table; - constvalue *cur = prev->next; - - while (cur!=NULL) { - if (strcmp(name,cur->name)==0) { - prev->next=cur->next; - free(cur); - return TRUE; - } /* if */ - prev=cur; - cur=cur->next; - } /* while */ - return FALSE; -} -#endif - -void delete_consttable(constvalue *table) -{ - constvalue *cur=table->next, *next; - - while (cur!=NULL) { - next=cur->next; - free(cur); - cur=next; - } /* while */ - memset(table,0,sizeof(constvalue)); -} - -/* add_constant - * - * Adds a symbol to the symbol table. Returns NULL on failure. - */ -symbol *add_constant(const char *name,cell val,int vclass,int tag) -{ - symbol *sym; - - /* Test whether a global or local symbol with the same name exists. Since - * constants are stored in the symbols table, this also finds previously - * defind constants. */ - sym=findglb(name,sSTATEVAR); - if (!sym) - sym=findloc(name); - if (sym) { - int redef=0; - if (sym->ident!=iCONSTEXPR) - redef=1; /* redefinition a function/variable to a constant is not allowed */ - if ((sym->usage & uENUMFIELD)!=0) { - /* enum field, special case if it has a different tag and the new symbol is also an enum field */ - constvalue *tagid; - symbol *tagsym; - if (sym->tag==tag) - redef=1; /* enumeration field is redefined (same tag) */ - tagid=find_tag_byval(tag); - if (tagid==NULL) { - redef=1; /* new constant does not have a tag */ - } else { - tagsym=findconst(tagid->name,NULL); - if (tagsym==NULL || (tagsym->usage & uENUMROOT)==0) - redef=1; /* new constant is not an enumeration field */ - } /* if */ - /* in this particular case (enumeration field that is part of a different - * enum, and non-conflicting with plain constants) we want to be able to - * redefine it - */ - if (!redef) - goto redef_enumfield; - } else if (!compare_tag(sym->tag, tag)) { - redef=1; /* redefinition of a constant (non-enum) to a different tag is not allowed */ - } /* if */ - if (redef) { - error(21,name); /* symbol already defined */ - return NULL; - } else if (sym->addr!=val) { - error(201,name); /* redefinition of constant (different value) */ - sym->addr=val; /* set new value */ - } /* if */ - /* silently ignore redefinitions of constants with the same value & tag */ - return sym; - } /* if */ - - /* constant doesn't exist yet (or is allowed to be redefined) */ -redef_enumfield: - sym=addsym(name,val,iCONSTEXPR,vclass,tag,uDEFINE); - assert(sym!=NULL); /* fatal error 103 must be given on error */ - if (sc_status == statIDLE) - sym->usage |= uPREDEF; - return sym; -} - -/* statement - The Statement Parser - * - * This routine is called whenever the parser needs to know what statement - * it encounters (i.e. whenever program syntax requires a statement). - */ -static void statement(int *lastindent,int allow_decl) -{ - int tok,save; - cell val; - char *st; - - if (!freading) { - error(36); /* empty statement */ - return; - } /* if */ - errorset(sRESET,0); - - tok=lex(&val,&st); - if (tok!='{') { - insert_dbgline(fline); - setline(TRUE); - } /* if */ - /* lex() has set stmtindent */ - if (lastindent!=NULL && tok!=tLABEL) { - if (*lastindent>=0 && *lastindent!=stmtindent && !indent_nowarn && sc_tabsize>0) - error(217); /* loose indentation */ - *lastindent=stmtindent; - indent_nowarn=FALSE; /* if warning was blocked, re-enable it */ - } /* if */ - - if (tok == tSYMBOL) { - // We reaaaally don't have enough lookahead for this, so we cheat and try - // to determine whether this is probably a declaration. - int is_decl = FALSE; - if (matchtoken('[')) { - if (lexpeek(']')) - is_decl = TRUE; - lexpush(); - } else if (lexpeek(tSYMBOL)) { - is_decl = TRUE; - } - - if (is_decl) { - if (!allow_decl) { - error(3); - return; - } - lexpush(); - autozero = TRUE; - lastst = tNEW; - declloc(tNEWDECL); - return; - } - } - - switch (tok) { - case 0: - /* nothing */ - break; - case tINT: - case tVOID: - case tCHAR: - case tOBJECT: - lexpush(); - // Fall-through. - case tDECL: - case tSTATIC: - case tNEW: - if (!allow_decl) { - error(3); - break; - } - autozero = (tok != tDECL); - lastst = (tok == tDECL) ? tDECL : tNEW; - declloc(tok); - break; - case tDELETE: - dodelete(); - lastst=tDELETE; - break; - case '{': - case tBEGIN: - save=fline; - if (!matchtoken('}')) { /* {} is the empty statement */ - compound(save==fline,tok); - } else { - lastst = tEMPTYBLOCK; - } - /* lastst (for "last statement") does not change - you're not my father, don't tell me what to do */ - break; - case ';': - error(36); /* empty statement */ - break; - case tIF: - lastst=doif(); - break; - case tWHILE: - lastst=dowhile(); - break; - case tDO: - lastst=dodo(); - break; - case tFOR: - lastst=dofor(); - break; - case tSWITCH: - doswitch(); - lastst=tSWITCH; - break; - case tCASE: - case tDEFAULT: - error(14); /* not in switch */ - break; - case tGOTO: - dogoto(); - lastst=tGOTO; - break; - case tLABEL: - dolabel(); - lastst=tLABEL; - break; - case tRETURN: - doreturn(); - lastst=tRETURN; - break; - case tBREAK: - dobreak(); - lastst=tBREAK; - break; - case tCONTINUE: - docont(); - lastst=tCONTINUE; - break; - case tEXIT: - doexit(); - lastst=tEXIT; - break; - case tASSERT: - doassert(); - lastst=tASSERT; - break; - case tSLEEP: - dosleep(); - lastst=tSLEEP; - break; - case tCONST: - decl_const(sLOCAL); - break; - case tENUM: - decl_enum(sLOCAL); - break; - default: /* non-empty expression */ - sc_allowproccall=optproccall; - lexpush(); /* analyze token later */ - doexpr(TRUE,TRUE,TRUE,TRUE,NULL,NULL,FALSE); - needtoken(tTERM); - lastst=tEXPR; - sc_allowproccall=FALSE; - } /* switch */ -} - -static void compound(int stmt_sameline,int starttok) -{ - int indent=-1; - cell save_decl=declared; - int count_stmt=0; - int block_start=fline; /* save line where the compound block started */ - int endtok; - - pushstacklist(); - pushheaplist(); - /* if there is more text on this line, we should adjust the statement indent */ - if (stmt_sameline) { - int i; - const unsigned char *p=lptr; - /* go back to the opening brace */ - while (*p!=starttok) { - assert(p>pline); - p--; - } /* while */ - assert(*p==starttok); /* it should be found */ - /* go forward, skipping white-space */ - p++; - while (*p<=' ' && *p!='\0') - p++; - assert(*p!='\0'); /* a token should be found */ - stmtindent=0; - for (i=0; i<(int)(p-pline); i++) - if (pline[i]=='\t' && sc_tabsize>0) - stmtindent += (int)(sc_tabsize - (stmtindent+sc_tabsize) % sc_tabsize); - else - stmtindent++; - } /* if */ - - endtok=(starttok=='{') ? '}' : tEND; - nestlevel+=1; /* increase compound statement level */ - while (matchtoken(endtok)==0){/* repeat until compound statement is closed */ - if (!freading){ - error(30,block_start); /* compound block not closed at end of file */ - break; - } else { - if (count_stmt>0 && (lastst==tRETURN || lastst==tBREAK || lastst==tCONTINUE || lastst==tENDLESS)) - error(225); /* unreachable code */ - statement(&indent,TRUE); /* do a statement */ - count_stmt++; - } /* if */ - } /* while */ - if (lastst!=tRETURN) - destructsymbols(&loctab,nestlevel); - if (lastst!=tRETURN && lastst!=tGOTO) { - popheaplist(); - popstacklist(1); - } else { - popheaplist(); - popstacklist(0); - } - testsymbols(&loctab,nestlevel,FALSE,TRUE); /* look for unused block locals */ - declared=save_decl; - delete_symbols(&loctab,nestlevel,FALSE,TRUE); /* erase local symbols, but - * retain block local labels - * (within the function) */ - nestlevel-=1; /* decrease compound statement level */ -} - -/* doexpr - * - * Global references: stgidx (referred to only) - */ -static int doexpr(int comma,int chkeffect,int allowarray,int mark_endexpr, - int *tag,symbol **symptr,int chkfuncresult) -{ - return doexpr2(comma,chkeffect,allowarray,mark_endexpr,tag,symptr,chkfuncresult,NULL); -} - -/* doexpr2 - * - * Global references: stgidx (referred to only) - */ -static int doexpr2(int comma,int chkeffect,int allowarray,int mark_endexpr, - int *tag,symbol **symptr,int chkfuncresult,value *lval) -{ - int index,ident; - int localstaging=FALSE; - cell val; - - if (!staging) { - stgset(TRUE); /* start stage-buffering */ - localstaging=TRUE; - assert(stgidx==0); - } /* if */ - index=stgidx; - errorset(sEXPRMARK,0); - do { - /* on second round through, mark the end of the previous expression */ - if (index!=stgidx) - markexpr(sEXPR,NULL,0); - sideeffect=FALSE; - ident=expression(&val,tag,symptr,chkfuncresult,lval); - if (!allowarray && (ident==iARRAY || ident==iREFARRAY)) - error(33,"-unknown-"); /* array must be indexed */ - if (chkeffect && !sideeffect) - error(215); /* expression has no effect */ - sc_allowproccall=FALSE; /* cannot use "procedure call" syntax anymore */ - } while (comma && matchtoken(',')); /* more? */ - if (mark_endexpr) - markexpr(sEXPR,NULL,0); /* optionally, mark the end of the expression */ - errorset(sEXPRRELEASE,0); - if (localstaging) { - stgout(index); - stgset(FALSE); /* stop staging */ - } /* if */ - return ident; -} - -/* exprconst - */ -int exprconst(cell *val,int *tag,symbol **symptr) -{ - int ident,index; - cell cidx; - - stgset(TRUE); /* start stage-buffering */ - stgget(&index,&cidx); /* mark position in code generator */ - errorset(sEXPRMARK,0); - ident=expression(val,tag,symptr,FALSE,NULL); - stgdel(index,cidx); /* scratch generated code */ - stgset(FALSE); /* stop stage-buffering */ - if (ident!=iCONSTEXPR) { - error(8); /* must be constant expression */ - if (val!=NULL) - *val=0; - if (tag!=NULL) - *tag=0; - if (symptr!=NULL) - *symptr=NULL; - } /* if */ - errorset(sEXPRRELEASE,0); - return (ident==iCONSTEXPR); -} - -/* test - * - * In the case a "simple assignment" operator ("=") is used within a test, - * the warning "possibly unintended assignment" is displayed. This routine - * sets the global variable "sc_intest" to true, it is restored upon termination. - * In the case the assignment was intended, use parentheses around the - * expression to avoid the warning; primary() sets "sc_intest" to 0. - * - * Global references: sc_intest (altered, but restored upon termination) - */ -static int test(int label,int parens,int invert) -{ - int index,tok; - cell cidx; - int ident,tag; - int endtok; - cell constval; - symbol *sym; - int localstaging=FALSE; - - if (!staging) { - stgset(TRUE); /* start staging */ - localstaging=TRUE; - #if !defined NDEBUG - stgget(&index,&cidx); /* should start at zero if started locally */ - assert(index==0); - #endif - } /* if */ - - PUSHSTK_I(sc_intest); - sc_intest=TRUE; - endtok=0; - if (parens!=TEST_PLAIN) { - if (matchtoken('(')) - endtok=')'; - else if (parens==TEST_THEN) - endtok=tTHEN; - else if (parens==TEST_DO) - endtok=tDO; - } /* if */ - do { - stgget(&index,&cidx); /* mark position (of last expression) in - * code generator */ - ident=expression(&constval,&tag,&sym,TRUE,NULL); - tok=matchtoken(','); - if (tok) - markexpr(sEXPR,NULL,0); - } while (tok); /* do */ - if (endtok!=0) - needtoken(endtok); - if (ident==iARRAY || ident==iREFARRAY) { - const char *ptr=sym->name; - error(33,ptr); /* array must be indexed */ - } /* if */ - if (ident==iCONSTEXPR) { /* constant expression */ - int testtype=0; - sc_intest=(short)POPSTK_I();/* restore stack */ - stgdel(index,cidx); - if (constval) { /* code always executed */ - error(206); /* redundant test: always non-zero */ - testtype=tENDLESS; - } else { - error(205); /* redundant code: never executed */ - jumplabel(label); - } /* if */ - if (localstaging) { - stgout(0); /* write "jumplabel" code */ - stgset(FALSE); /* stop staging */ - } /* if */ - return testtype; - } /* if */ - if (tag!=0 && tag!=pc_tag_bool) { - if (check_userop(lneg,tag,0,1,NULL,&tag)) - invert= !invert; /* user-defined ! operator inverted result */ - } - if (invert) - jmp_ne0(label); /* jump to label if true (different from 0) */ - else - jmp_eq0(label); /* jump to label if false (equal to 0) */ - markexpr(sEXPR,NULL,0); /* end expression (give optimizer a chance) */ - sc_intest=(short)POPSTK_I(); /* double typecast to avoid warning with Microsoft C */ - if (localstaging) { - stgout(0); /* output queue from the very beginning (see - * assert() when localstaging is set to TRUE) */ - stgset(FALSE); /* stop staging */ - } /* if */ - return 0; -} - -static int doif(void) -{ - int flab1,flab2; - int ifindent; - int lastst_true; - - ifindent=stmtindent; /* save the indent of the "if" instruction */ - flab1=getlabel(); /* get label number for false branch */ - test(flab1,TEST_THEN,FALSE); /* get expression, branch to flab1 if false */ - statement(NULL,FALSE); /* if true, do a statement */ - if (!matchtoken(tELSE)) { /* if...else ? */ - setlabel(flab1); /* no, simple if..., print false label */ - } else { - lastst_true=lastst; /* save last statement of the "true" branch */ - /* to avoid the "dangling else" error, we want a warning if the "else" - * has a lower indent than the matching "if" */ - if (stmtindent0) - error(217); /* loose indentation */ - flab2=getlabel(); - if ((lastst!=tRETURN) && (lastst!=tGOTO)) - jumplabel(flab2); /* "true" branch jumps around "else" clause, unless the "true" branch statement already jumped */ - setlabel(flab1); /* print false label */ - statement(NULL,FALSE); /* do "else" clause */ - setlabel(flab2); /* print true label */ - /* if both the "true" branch and the "false" branch ended with the same - * kind of statement, set the last statement id to that kind, rather than - * to the generic tIF; this allows for better "unreachable code" checking - */ - if (lastst==lastst_true) - return lastst; - } /* if */ - return tIF; -} - -static int dowhile(void) -{ - int wq[wqSIZE]; /* allocate local queue */ - int save_endlessloop,retcode; - - save_endlessloop=endlessloop; - addwhile(wq); /* add entry to queue for "break" */ - setlabel(wq[wqLOOP]); /* loop label */ - /* The debugger uses the "break" opcode to be able to "break" out of - * a loop. To make sure that each loop has a break opcode, even for the - * tiniest loop, set it below the top of the loop - */ - setline(TRUE); - endlessloop=test(wq[wqEXIT],TEST_DO,FALSE);/* branch to wq[wqEXIT] if false */ - statement(NULL,FALSE); /* if so, do a statement */ - jumplabel(wq[wqLOOP]); /* and loop to "while" start */ - setlabel(wq[wqEXIT]); /* exit label */ - delwhile(); /* delete queue entry */ - - retcode=endlessloop ? tENDLESS : tWHILE; - endlessloop=save_endlessloop; - return retcode; -} - -/* - * Note that "continue" will in this case not jump to the top of the loop, but - * to the end: just before the TRUE-or-FALSE testing code. - */ -static int dodo(void) -{ - int wq[wqSIZE],top; - int save_endlessloop,retcode; - - save_endlessloop=endlessloop; - addwhile(wq); /* see "dowhile" for more info */ - top=getlabel(); /* make a label first */ - setlabel(top); /* loop label */ - statement(NULL,FALSE); - needtoken(tWHILE); - setlabel(wq[wqLOOP]); /* "continue" always jumps to WQLOOP. */ - setline(TRUE); - endlessloop=test(wq[wqEXIT],TEST_OPT,FALSE); - jumplabel(top); - setlabel(wq[wqEXIT]); - delwhile(); - needtoken(tTERM); - - retcode=endlessloop ? tENDLESS : tDO; - endlessloop=save_endlessloop; - return retcode; -} - -static int dofor(void) -{ - int wq[wqSIZE],skiplab; - cell save_decl; - int save_nestlevel,save_endlessloop; - int index,endtok; - int *ptr; - - save_decl=declared; - save_nestlevel=nestlevel; - save_endlessloop=endlessloop; - pushstacklist(); - - addwhile(wq); - skiplab=getlabel(); - endtok= matchtoken('(') ? ')' : tDO; - if (matchtoken(';')==0) { - /* new variable declarations are allowed here */ - token_t tok; - - switch (lextok(&tok)) { - case tINT: - case tCHAR: - case tOBJECT: - case tVOID: - lexpush(); - // Fallthrough. - case tNEW: - /* The variable in expr1 of the for loop is at a - * 'compound statement' level of it own. - */ - nestlevel++; - autozero=1; - declloc(tok.id); /* declare local variable */ - break; - case tSYMBOL: - { - // See comment in statement() near tSYMBOL. - int is_decl = FALSE; - if (matchtoken('[')) { - if (lexpeek(']')) - is_decl = TRUE; - lexpush(); - } else if (lexpeek(tSYMBOL)) { - is_decl = TRUE; - } - - if (is_decl) { - lexpush(); - nestlevel++; - autozero=1; - declloc(tSYMBOL); - break; - } - - // Fall-through to default! - } - default: - lexpush(); - doexpr(TRUE,TRUE,TRUE,TRUE,NULL,NULL,FALSE); /* expression 1 */ - needtoken(';'); - break; - } - } /* if */ - /* Adjust the "declared" field in the "while queue", in case that - * local variables were declared in the first expression of the - * "for" loop. These are deleted in separately, so a "break" or a "continue" - * must ignore these fields. - */ - ptr=readwhile(); - assert(ptr!=NULL); - /*ptr[wqBRK]=(int)declared; - *ptr[wqCONT]=(int)declared; - */ - ptr[wqBRK] = stackusage->list_id; - ptr[wqCONT] = stackusage->list_id; - jumplabel(skiplab); /* skip expression 3 1st time */ - setlabel(wq[wqLOOP]); /* "continue" goes to this label: expr3 */ - setline(TRUE); - /* Expressions 2 and 3 are reversed in the generated code: expression 3 - * precedes expression 2. When parsing, the code is buffered and marks for - * the start of each expression are insterted in the buffer. - */ - assert(!staging); - stgset(TRUE); /* start staging */ - assert(stgidx==0); - index=stgidx; - stgmark(sSTARTREORDER); - stgmark((char)(sEXPRSTART+0)); /* mark start of 2nd expression in stage */ - setlabel(skiplab); /* jump to this point after 1st expression */ - if (matchtoken(';')) { - endlessloop=1; - } else { - endlessloop=test(wq[wqEXIT],TEST_PLAIN,FALSE);/* expression 2 (jump to wq[wqEXIT] if false) */ - needtoken(';'); - } /* if */ - stgmark((char)(sEXPRSTART+1)); /* mark start of 3th expression in stage */ - if (!matchtoken(endtok)) { - doexpr(TRUE,TRUE,TRUE,TRUE,NULL,NULL,FALSE); /* expression 3 */ - needtoken(endtok); - } /* if */ - stgmark(sENDREORDER); /* mark end of reversed evaluation */ - stgout(index); - stgset(FALSE); /* stop staging */ - statement(NULL,FALSE); - jumplabel(wq[wqLOOP]); - setlabel(wq[wqEXIT]); - delwhile(); - - assert(nestlevel>=save_nestlevel); - if (nestlevel>save_nestlevel) { - /* Clean up the space and the symbol table for the local - * variable in "expr1". - */ - destructsymbols(&loctab,nestlevel); - popstacklist(1); - testsymbols(&loctab,nestlevel,FALSE,TRUE); /* look for unused block locals */ - declared=save_decl; - delete_symbols(&loctab,nestlevel,FALSE,TRUE); - nestlevel=save_nestlevel; /* reset 'compound statement' nesting level */ - } else { - popstacklist(0); - } /* if */ - - index=endlessloop ? tENDLESS : tFOR; - endlessloop=save_endlessloop; - return index; -} - -/* The switch statement is incompatible with its C sibling: - * 1. the cases are not drop through - * 2. only one instruction may appear below each case, use a compound - * instruction to execute multiple instructions - * 3. the "case" keyword accepts a comma separated list of values to - * match - * - * SWITCH param - * PRI = expression result - * param = table offset (code segment) - * - */ -static void doswitch(void) -{ - int lbl_table,lbl_exit,lbl_case; - int swdefault,casecount; - int tok,endtok; - cell val; - char *str; - constvalue caselist = { NULL, "", 0, 0}; /* case list starts empty */ - constvalue *cse,*csp; - char labelname[sNAMEMAX+1]; - - endtok= matchtoken('(') ? ')' : tDO; - doexpr(TRUE,FALSE,FALSE,FALSE,NULL,NULL,TRUE);/* evaluate switch expression */ - needtoken(endtok); - /* generate the code for the switch statement, the label is the address - * of the case table (to be generated later). - */ - lbl_table=getlabel(); - lbl_case=0; /* just to avoid a compiler warning */ - ffswitch(lbl_table); - - if (matchtoken(tBEGIN)) { - endtok=tEND; - } else { - endtok='}'; - needtoken('{'); - } /* if */ - lbl_exit=getlabel(); /* get label number for jumping out of switch */ - swdefault=FALSE; - casecount=0; - do { - tok=lex(&val,&str); /* read in (new) token */ - switch (tok) { - case tCASE: - if (swdefault!=FALSE) - error(15); /* "default" case must be last in switch statement */ - lbl_case=getlabel(); - PUSHSTK_I(sc_allowtags); - sc_allowtags=FALSE; /* do not allow tagnames here */ - do { - casecount++; - - /* ??? enforce/document that, in a switch, a statement cannot start - * with a label. Then, you can search for: - * * the first semicolon (marks the end of a statement) - * * an opening brace (marks the start of a compound statement) - * and search for the right-most colon before that statement - * Now, by replacing the ':' by a special COLON token, you can - * parse all expressions until that special token. - */ - - exprconst(&val,NULL,NULL); - /* Search the insertion point (the table is kept in sorted order, so - * that advanced abstract machines can sift the case table with a - * binary search). Check for duplicate case values at the same time. - */ - for (csp=&caselist, cse=caselist.next; - cse!=NULL && cse->valuenext) - /* nothing */; - if (cse!=NULL && cse->value==val) - error(40,val); /* duplicate "case" label */ - /* Since the label is stored as a string in the "constvalue", the - * size of an identifier must be at least 8, as there are 8 - * hexadecimal digits in a 32-bit number. - */ - #if sNAMEMAX < 8 - #error Length of identifier (sNAMEMAX) too small. - #endif - assert(csp!=NULL); - assert(csp->next==cse); - insert_constval(csp,cse,itoh(lbl_case),val,0); - if (matchtoken(tDBLDOT)) { - error(1, ":", ".."); - } /* if */ - } while (matchtoken(',')); - needtoken(':'); /* ':' ends the case */ - sc_allowtags=(short)POPSTK_I(); /* reset */ - setlabel(lbl_case); - statement(NULL,FALSE); - jumplabel(lbl_exit); - break; - case tDEFAULT: - if (swdefault!=FALSE) - error(16); /* multiple defaults in switch */ - lbl_case=getlabel(); - setlabel(lbl_case); - needtoken(':'); - swdefault=TRUE; - statement(NULL,FALSE); - /* Jump to lbl_exit, even thouh this is the last clause in the - * switch, because the jump table is generated between the last - * clause of the switch and the exit label. - */ - jumplabel(lbl_exit); - break; - default: - if (tok!=endtok) { - error(2); - indent_nowarn=TRUE; /* disable this check */ - tok=endtok; /* break out of the loop after an error */ - } /* if */ - } /* switch */ - } while (tok!=endtok); - - #if !defined NDEBUG - /* verify that the case table is sorted (unfortunatly, duplicates can - * occur; there really shouldn't be duplicate cases, but the compiler - * may not crash or drop into an assertion for a user error). */ - for (cse=caselist.next; cse!=NULL && cse->next!=NULL; cse=cse->next) - assert(cse->value <= cse->next->value); - #endif - /* generate the table here, before lbl_exit (general jump target) */ - setlabel(lbl_table); - assert(swdefault==FALSE || swdefault==TRUE); - if (swdefault==FALSE) { - /* store lbl_exit as the "none-matched" label in the switch table */ - strcpy(labelname,itoh(lbl_exit)); - } else { - /* lbl_case holds the label of the "default" clause */ - strcpy(labelname,itoh(lbl_case)); - } /* if */ - ffcase(casecount,labelname,TRUE); - /* generate the rest of the table */ - for (cse=caselist.next; cse!=NULL; cse=cse->next) - ffcase(cse->value,cse->name,FALSE); - - setlabel(lbl_exit); - delete_consttable(&caselist); /* clear list of case labels */ -} - -static void doassert(void) -{ - int flab1,index; - cell cidx; - - if ((sc_debug & sCHKBOUNDS)!=0) { - flab1=getlabel(); /* get label number for "OK" branch */ - test(flab1,TEST_PLAIN,TRUE);/* get expression and branch to flab1 if true */ - insert_dbgline(fline); /* make sure we can find the correct line number */ - ffabort(xASSERTION); - setlabel(flab1); - } else { - stgset(TRUE); /* start staging */ - stgget(&index,&cidx); /* mark position in code generator */ - do { - expression(NULL,NULL,NULL,FALSE,NULL); - stgdel(index,cidx); /* just scrap the code */ - } while (matchtoken(',')); - stgset(FALSE); /* stop staging */ - } /* if */ - needtoken(tTERM); -} - -static void dogoto(void) -{ - char *st; - cell val; - symbol *sym; - - /* if we were inside an endless loop, assume that we jump out of it */ - endlessloop=0; - - error(4, "goto"); - - if (lex(&val,&st)==tSYMBOL) { - sym=fetchlab(st); - jumplabel((int)sym->addr); - sym->usage|=uREAD; /* set "uREAD" bit */ - // ??? if the label is defined (check sym->usage & uDEFINE), check - // sym->compound (nesting level of the label) against nestlevel; - // if sym->compound < nestlevel, call the destructor operator - } else { - error(20,st); /* illegal symbol name */ - } /* if */ - needtoken(tTERM); -} - -static void dolabel(void) -{ - char *st; - cell val; - symbol *sym; - - tokeninfo(&val,&st); /* retrieve label name again */ - if (find_constval(&tagname_tab,st,0)!=NULL) - error(221,st); /* label name shadows tagname */ - sym=fetchlab(st); - setlabel((int)sym->addr); - /* since one can jump around variable declarations or out of compound - * blocks, the stack must be manually adjusted - */ - //:TODO: This is actually generated, egads! - //We have to support this and LCTRL/SCTRL - setstk(-declared*sizeof(cell)); - sym->usage|=uDEFINE; /* label is now defined */ -} - -/* fetchlab - * - * Finds a label from the (local) symbol table or adds one to it. - * Labels are local in scope. - * - * Note: The "_usage" bit is set to zero. The routines that call "fetchlab()" - * must set this bit accordingly. - */ -static symbol *fetchlab(char *name) -{ - symbol *sym; - - sym=findloc(name); /* labels are local in scope */ - if (sym){ - if (sym->ident!=iLABEL) - error(19,sym->name); /* not a label: ... */ - } else { - sym=addsym(name,getlabel(),iLABEL,sLOCAL,0,0); - assert(sym!=NULL); /* fatal error 103 must be given on error */ - sym->x.declared=(int)declared; - sym->compound=nestlevel; - } /* if */ - return sym; -} - -static int is_variadic(symbol *sym) -{ - assert(sym->ident==iFUNCTN); - arginfo *arg = sym->dim.arglist; - while (arg->ident) { - if (arg->ident == iVARARGS) - return TRUE; - arg++; - } - return FALSE; -} - -/* doreturn - * - * Global references: rettype (altered) - */ -static void doreturn(void) -{ - int tag,ident; - int level; - symbol *sym,*sub; - - if (!matchtoken(tTERM)) { - /* "return " */ - if ((rettype & uRETNONE)!=0) - error(78); /* mix "return;" and "return value;" */ - ident=doexpr(TRUE,FALSE,TRUE,FALSE,&tag,&sym,TRUE); - needtoken(tTERM); - if (ident==iARRAY && sym==NULL) { - /* returning a literal string is not supported (it must be a variable) */ - error(39); - ident=iCONSTEXPR; /* avoid handling an "array" case */ - } /* if */ - /* see if this function already has a sub type (an array attached) */ - sub=finddepend(curfunc); - assert(sub==NULL || sub->ident==iREFARRAY); - if ((rettype & uRETVALUE)!=0) { - int retarray=(ident==iARRAY || ident==iREFARRAY); - /* there was an earlier "return" statement in this function */ - if ((sub==NULL && retarray) || (sub!=NULL && !retarray)) - error(79); /* mixing "return array;" and "return value;" */ - if (retarray && (curfunc->usage & uPUBLIC)!=0) - error(90,curfunc->name); /* public function may not return array */ - } /* if */ - rettype|=uRETVALUE; /* function returns a value */ - /* check tagname with function tagname */ - assert(curfunc!=NULL); - if (!matchtag_string(ident, tag)) - matchtag(curfunc->tag,tag,TRUE); - if (ident==iARRAY || ident==iREFARRAY) { - int dim[sDIMEN_MAX], numdim = 0; - cell arraysize; - assert(sym!=NULL); - if (sub!=NULL) { - assert(sub->ident==iREFARRAY); - /* this function has an array attached already; check that the current - * "return" statement returns exactly the same array - */ - level=sym->dim.array.level; - if (sub->dim.array.level!=level) { - error(48); /* array dimensions must match */ - } else { - for (numdim=0; numdim<=level; numdim++) { - dim[numdim]=(int)sub->dim.array.length; - if (sym->dim.array.length!=dim[numdim]) - error(47); /* array sizes must match */ - if (numdimdim.array.level; - for (numdim=0; numdim<=level; numdim++) { - dim[numdim]=(int)sub->dim.array.length; - idxtag[numdim]=sub->x.tags.index; - if (numdimname); - } /* for */ - if (sym->tag==pc_tag_string && numdim!=0) - slength=dim[numdim-1]; - /* the address of the array is stored in a hidden parameter; the address - * of this parameter is 1 + the number of parameters (times the size of - * a cell) + the size of the stack frame and the return address - * base + 0*sizeof(cell) == previous "base" - * base + 1*sizeof(cell) == function return address - * base + 2*sizeof(cell) == number of arguments - * base + 3*sizeof(cell) == first argument of the function - * ... - * base + ((n-1)+3)*sizeof(cell) == last argument of the function - * base + (n+3)*sizeof(cell) == hidden parameter with array address - */ - assert(curfunc!=NULL); - assert(curfunc->dim.arglist!=NULL); - for (argcount=0; curfunc->dim.arglist[argcount].ident!=0; argcount++) - /* nothing */; - sub=addvariable2(curfunc->name,(argcount+3)*sizeof(cell),iREFARRAY,sGLOBAL,curfunc->tag,dim,numdim,idxtag,slength); - sub->parent=curfunc; - } /* if */ - /* get the hidden parameter, copy the array (the array is on the heap; - * it stays on the heap for the moment, and it is removed -usually- at - * the end of the expression/statement, see expression() in SC3.C) - */ - if (is_variadic(curfunc)) { - load_hidden_arg(); - } else { - address(sub,sALT); /* ALT = destination */ - } - arraysize=calc_arraysize(dim,numdim,0); - memcopy(arraysize*sizeof(cell)); /* source already in PRI */ - /* moveto1(); is not necessary, callfunction() does a popreg() */ - } /* if */ - } else { - /* this return statement contains no expression */ - ldconst(0,sPRI); - if ((rettype & uRETVALUE)!=0) { - char symname[2*sNAMEMAX+16]; /* allow space for user defined operators */ - assert(curfunc!=NULL); - funcdisplayname(symname,curfunc->name); - error(209,symname); /* function should return a value */ - } /* if */ - rettype|=uRETNONE; /* function does not return anything */ - } /* if */ - destructsymbols(&loctab,0); /* call destructor for *all* locals */ - genheapfree(-1); - genstackfree(-1); /* free everything on the stack */ - ffret(strcmp(curfunc->name,uENTRYFUNC)!=0); -} - -static void dobreak(void) -{ - int *ptr; - - endlessloop=0; /* if we were inside an endless loop, we just jumped out */ - ptr=readwhile(); /* readwhile() gives an error if not in loop */ - needtoken(tTERM); - if (ptr==NULL) - return; - destructsymbols(&loctab,nestlevel); - genstackfree(ptr[wqBRK]); - jumplabel(ptr[wqEXIT]); -} - -static void docont(void) -{ - int *ptr; - - ptr=readwhile(); /* readwhile() gives an error if not in loop */ - needtoken(tTERM); - if (ptr==NULL) - return; - destructsymbols(&loctab,nestlevel); - genstackfree(ptr[wqCONT]); - genheapfree(ptr[wqCONT]); - jumplabel(ptr[wqLOOP]); -} - -static void doexit(void) -{ - int tag=0; - - if (matchtoken(tTERM)==0){ - doexpr(TRUE,FALSE,FALSE,TRUE,&tag,NULL,TRUE); - needtoken(tTERM); - } else { - ldconst(0,sPRI); - } /* if */ - ldconst(tag,sALT); - destructsymbols(&loctab,0); /* call destructor for *all* locals */ - ffabort(xEXIT); -} - -static void dosleep(void) -{ - int tag=0; - - if (matchtoken(tTERM)==0){ - doexpr(TRUE,FALSE,FALSE,TRUE,&tag,NULL,TRUE); - needtoken(tTERM); - } else { - ldconst(0,sPRI); - } /* if */ - ldconst(tag,sALT); - ffabort(xSLEEP); - - /* for stack usage checking, mark the use of the sleep instruction */ - pc_memflags |= suSLEEP_INSTR; -} - -static void dostate(void) -{ - char name[sNAMEMAX+1]; - constvalue *automaton; - constvalue *state; - constvalue *stlist; - int flabel; - symbol *sym; - #if !defined SC_LIGHT - int length,index,listid,listindex,stateindex; - char *doc; - #endif - - /* check for an optional condition */ - if (matchtoken('(')) { - flabel=getlabel(); /* get label number for "false" branch */ - pc_docexpr=TRUE; /* attach expression as a documentation string */ - test(flabel,TEST_PLAIN,FALSE);/* get expression, branch to flabel if false */ - pc_docexpr=FALSE; - needtoken(')'); - } else { - flabel=-1; - } /* if */ - - if (!sc_getstateid(&automaton,&state)) { - delete_autolisttable(); - return; - } /* if */ - needtoken(tTERM); - - /* store the new state id */ - assert(state!=NULL); - ldconst(state->value,sPRI); - assert(automaton!=NULL); - assert((automaton->index==0 && automaton->name[0]=='\0') || automaton->index>0); - storereg(automaton->value,sPRI); - - /* find the optional entry() function for the state */ - sym=findglb(uENTRYFUNC,sGLOBAL); - if (sc_status==statWRITE && sym!=NULL && sym->ident==iFUNCTN && sym->states!=NULL) { - for (stlist=sym->states->next; stlist!=NULL; stlist=stlist->next) { - assert(strlen(stlist->name)!=0); - if (state_getfsa(stlist->index)==automaton->index && state_inlist(stlist->index,(int)state->value)) - break; /* found! */ - } /* for */ - assert(stlist==NULL || state_inlist(stlist->index,state->value)); - if (stlist!=NULL) { - /* the label to jump to is in stlist->name */ - ffcall(sym,stlist->name,0); - } /* if */ - } /* if */ - - if (flabel>=0) - setlabel(flabel); /* condition was false, jump around the state switch */ - - #if !defined SC_LIGHT - /* mark for documentation */ - if (sc_status==statFIRST) { - char *str; - /* get the last list id attached to the function, this contains the source states */ - assert(curfunc!=NULL); - if (curfunc->states!=NULL) { - stlist=curfunc->states->next; - assert(stlist!=NULL); - while (stlist->next!=NULL) - stlist=stlist->next; - listid=stlist->index; - } else { - listid=-1; - } /* if */ - listindex=0; - length=strlen(name)+70; /* +70 for the fixed part "\n" */ - /* see if there are any condition strings to attach */ - for (index=0; (str=get_autolist(index))!=NULL; index++) - length+=strlen(str); - if ((doc=(char*)malloc(length*sizeof(char)))!=NULL) { - do { - sprintf(doc,"=0) { - /* get the source state */ - stateindex=state_listitem(listid,listindex); - state=state_findid(stateindex); - assert(state!=NULL); - sprintf(doc+strlen(doc)," source=\"%s\"",state->name); - } /* if */ - if (get_autolist(0)!=NULL) { - /* add the condition */ - strcat(doc," condition=\""); - for (index=0; (str=get_autolist(index))!=NULL; index++) { - /* remove the ')' token that may be appended before detecting that the expression has ended */ - if (*str!=')' || *(str+1)!='\0' || get_autolist(index+1)!=NULL) - strcat(doc,str); - } /* for */ - strcat(doc,"\""); - } /* if */ - strcat(doc,"/>\n"); - insert_docstring(doc); - } while (listid>=0 && ++listindexlist_id; /* stack pointer (for "break") */ - ptr[wqCONT]=stackusage->list_id; /* for "continue", possibly adjusted later */ - ptr[wqLOOP]=getlabel(); - ptr[wqEXIT]=getlabel(); - if (wqptr>=(wq+wqTABSZ-wqSIZE)) - error(FATAL_ERROR_ALLOC_OVERFLOW,"loop table"); /* loop table overflow (too many active loops)*/ - k=0; - while (kwq) - wqptr-=wqSIZE; -} - -static int *readwhile(void) -{ - if (wqptr<=wq){ - error(24); /* out of context */ - return NULL; - } else { - return (wqptr-wqSIZE); - } /* if */ -} - -bool typeinfo_t::isCharArray() const -{ - return numdim == 1 && tag == pc_tag_string; -} diff --git a/sourcepawn/compiler/sc2.cpp b/sourcepawn/compiler/sc2.cpp deleted file mode 100644 index aeca1967..00000000 --- a/sourcepawn/compiler/sc2.cpp +++ /dev/null @@ -1,3274 +0,0 @@ -// vim: set ts=8 sts=2 sw=2 tw=99 et: -/* Pawn compiler - File input, preprocessing and lexical analysis functions - * - * Copyright (c) ITB CompuPhase, 1997-2006 - * - * This software is provided "as-is", without any express or implied warranty. - * In no event will the authors be held liable for any damages arising from - * the use of this software. - * - * Permission is granted to anyone to use this software for any purpose, - * including commercial applications, and to alter it and redistribute it - * freely, subject to the following restrictions: - * - * 1. The origin of this software must not be misrepresented; you must not - * claim that you wrote the original software. If you use this software in - * a product, an acknowledgment in the product documentation would be - * appreciated but is not required. - * 2. Altered source versions must be plainly marked as such, and must not be - * misrepresented as being the original software. - * 3. This notice may not be removed or altered from any source distribution. - * - * Version: $Id$ - */ -#include -#include -#include -#include -#include -#include -#include "lstring.h" -#include "sc.h" -#include "tokenbuffer.h" -#if defined LINUX || defined __FreeBSD__ || defined __OpenBSD__ - #include "sclinux.h" -#endif -#include "sp_symhash.h" - -#if defined FORTIFY - #include -#endif - -/* flags for litchar() */ -#define RAWMODE 0x1 -#define UTF8MODE 0x2 -#define ISPACKED 0x4 -static cell litchar(const unsigned char **lptr,int flags); -static symbol *find_symbol(const symbol *root,const char *name,int fnumber,int automaton,int *cmptag); - -static void substallpatterns(unsigned char *line,int buffersize); -static int match(const char *st,int end); -static int alpha(char c); - -#define SKIPMODE 1 /* bit field in "#if" stack */ -#define PARSEMODE 2 /* bit field in "#if" stack */ -#define HANDLED_ELSE 4 /* bit field in "#if" stack */ -#define SKIPPING (skiplevel>0 && (ifstack[skiplevel-1] & SKIPMODE)==SKIPMODE) - -static short icomment; /* currently in multiline comment? */ -static char ifstack[sCOMP_STACK]; /* "#if" stack */ -static short iflevel; /* nesting level if #if/#else/#endif */ -static short skiplevel; /* level at which we started skipping (including nested #if .. #endif) */ -static unsigned char term_expr[] = ""; -static int listline=-1; /* "current line" for the list file */ - -#if defined DARWIN -static double pow10(double d) -{ - return pow(10, d); -} -#endif - -static bool sLiteralQueueDisabled = false; - -AutoDisableLiteralQueue::AutoDisableLiteralQueue() - : prev_value_(sLiteralQueueDisabled) -{ - sLiteralQueueDisabled = true; -} - -AutoDisableLiteralQueue::~AutoDisableLiteralQueue() -{ - sLiteralQueueDisabled = prev_value_; -} - -/* pushstk & popstk - * - * Uses a LIFO stack to store information. The stack is used by doinclude(), - * doswitch() (to hold the state of "swactive") and some other routines. - * - * Porting note: I made the bold assumption that an integer will not be - * larger than a pointer (it may be smaller). That is, the stack element - * is typedef'ed as a pointer type, but I also store integers on it. See - * SC.H for "stkitem" - * - * Global references: stack,stkidx,stktop (private to pushstk(), popstk() - * and clearstk()) - */ -static stkitem *stack=NULL; -static int stkidx=0,stktop=0; - -void pushstk(stkitem val) -{ - assert(stkidx<=stktop); - if (stkidx==stktop) { - stkitem *newstack; - int newsize= (stktop==0) ? 16 : 2*stktop; - /* try to resize the stack */ - assert(newsize>stktop); - newstack=(stkitem*)malloc(newsize*sizeof(stkitem)); - if (newstack==NULL) - error(FATAL_ERROR_ALLOC_OVERFLOW,"parser stack"); - /* swap the stacks */ - memcpy(newstack,stack,stkidx*sizeof(stkitem)); - if (stack!=NULL) - free(stack); - stack=newstack; - stktop=newsize; - } /* if */ - assert(stkidx'); /* termination character */ - lptr++; - while (*lptr<=' ' && *lptr!='\0') /* skip whitespace after quote */ - lptr++; - } else { - c='\0'; - } /* if */ - - i=0; - while (*lptr!=c && *lptr!='\0' && i0 && name[i-1]<=' ') - i--; /* strip trailing whitespace */ - assert(i'),TRUE); - if (!result && !silent) - error(FATAL_ERROR_READ,name); -} - -/* readline - * - * Reads in a new line from the input file pointed to by "inpf". readline() - * concatenates lines that end with a \ with the next line. If no more data - * can be read from the file, readline() attempts to pop off the previous file - * from the stack. If that fails too, it sets "freading" to 0. - * - * Global references: inpf,fline,inpfname,freading,icomment (altered) - */ -static void readline(unsigned char *line) -{ - int i,num,cont; - unsigned char *ptr; - - if (lptr==term_expr) - return; - num=sLINEMAX; - cont=FALSE; - do { - if (inpf==NULL || pc_eofsrc(inpf)) { - if (cont) - error(49); /* invalid line continuation */ - if (inpf!=NULL && inpf!=inpf_org) - pc_closesrc(inpf); - i=POPSTK_I(); - if (i==-1) { /* All's done; popstk() returns "stack is empty" */ - freading=FALSE; - *line='\0'; - /* when there is nothing more to read, the #if/#else stack should - * be empty and we should not be in a comment - */ - assert(iflevel>=0); - if (iflevel>0) - error(1,"#endif","-end of file-"); - else if (icomment!=0) - error(1,"*/","-end of file-"); - return; - } /* if */ - fline=i; - fcurrent=(short)POPSTK_I(); - icomment=(short)POPSTK_I(); - sc_is_utf8=(short)POPSTK_I(); - iflevel=(short)POPSTK_I(); - skiplevel=iflevel; /* this condition held before including the file */ - assert(!SKIPPING); /* idem ditto */ - curlibrary=(constvalue *)POPSTK_P(); - free(inpfname); /* return memory allocated for the include file name */ - inpfname=(char *)POPSTK_P(); - inpf=POPSTK_P(); - insert_dbgfile(inpfname); - setfiledirect(inpfname); - listline=-1; /* force a #line directive when changing the file */ - } /* if */ - - if (pc_readsrc(inpf,line,num)==NULL) { - *line='\0'; /* delete line */ - cont=FALSE; - } else { - /* check whether to erase leading spaces */ - if (cont) { - unsigned char *ptr=line; - while (*ptr<=' ' && *ptr!='\0') - ptr++; - if (ptr!=line) - memmove(line,ptr,strlen((char*)ptr)+1); - } /* if */ - cont=FALSE; - /* check whether a full line was read */ - if (strchr((char*)line,'\n')==NULL && !pc_eofsrc(inpf)) - error(75); /* line too long */ - /* check if the next line must be concatenated to this line */ - if ((ptr=(unsigned char*)strchr((char*)line,'\n'))==NULL) - ptr=(unsigned char*)strchr((char*)line,'\r'); - if (ptr!=NULL && ptr>line) { - assert(*(ptr+1)=='\0'); /* '\n' or '\r' should be last in the string */ - while (ptr>line && *ptr<=' ') - ptr--; /* skip trailing whitespace */ - if (*ptr=='\\') { - cont=TRUE; - /* set '\a' at the position of '\\' to make it possible to check - * for a line continuation in a single line comment (error 49) - */ - *ptr++='\a'; - *ptr='\0'; /* erase '\n' (and any trailing whitespace) */ - } /* if */ - } /* if */ - num-=strlen((char*)line); - line+=strlen((char*)line); - } /* if */ - fline+=1; - } while (num>=0 && cont); -} - -/* stripcom - * - * Replaces all comments from the line by space characters. It updates - * a global variable ("icomment") for multiline comments. - * - * This routine also supports the C++ extension for single line comments. - * These comments are started with "//" and end at the end of the line. - * - * The function also detects (and manages) "documentation comments". The - * global variable "icomment" is set to 2 for documentation comments. - * - * Global references: icomment (private to "stripcom") - */ -static void stripcom(unsigned char *line) -{ - char c; - #if !defined SC_LIGHT - #define COMMENT_LIMIT 100 - #define COMMENT_MARGIN 40 /* length of the longest word */ - char comment[COMMENT_LIMIT+COMMENT_MARGIN]; - int commentidx=0; - int skipstar=TRUE; - static int prev_singleline=FALSE; - int singleline=prev_singleline; - - prev_singleline=FALSE; /* preset */ - #endif - - while (*line){ - if (icomment!=0) { - if (*line=='*' && *(line+1)=='/') { - #if !defined SC_LIGHT - if (icomment==2) { - assert(commentidx0) - insert_docstring(comment); - } /* if */ - #endif - icomment=0; /* comment has ended */ - *line=' '; /* replace '*' and '/' characters by spaces */ - *(line+1)=' '; - line+=2; - } else { - if (*line=='/' && *(line+1)=='*') - error(216); /* nested comment */ - #if !defined SC_LIGHT - /* collect the comment characters in a string */ - if (icomment==2) { - if (skipstar && ((*line!='\0' && *line<=' ') || *line=='*')) { - /* ignore leading whitespace and '*' characters */ - } else if (commentidxCOMMENT_LIMIT && *line!='\0' && *line<=' ') { - comment[commentidx]='\0'; - insert_docstring(comment); - commentidx=0; - } /* if */ - skipstar=FALSE; - } /* if */ - } /* if */ - #endif - *line=' '; /* replace comments by spaces */ - line+=1; - } /* if */ - } else { - if (*line=='/' && *(line+1)=='*'){ - icomment=1; /* start comment */ - #if !defined SC_LIGHT - /* there must be two "*" behind the slash and then white space */ - if (*(line+2)=='*' && *(line+3)<=' ') { - /* if we are not in a function, we must attach the previous block - * to the global documentation - */ - if (curfunc==NULL && get_docstring(0)!=NULL) - sc_attachdocumentation(NULL); - icomment=2; /* documentation comment */ - } /* if */ - commentidx=0; - skipstar=TRUE; - #endif - *line=' '; /* replace '/' and '*' characters by spaces */ - *(line+1)=' '; - line+=2; - if (icomment==2) - *line++=' '; - } else if (*line=='/' && *(line+1)=='/'){ /* comment to end of line */ - if (strchr((char*)line,'\a')!=NULL) - error(49); /* invalid line continuation */ - #if !defined SC_LIGHT - if (*(line+2)=='/' && *(line+3)<=' ') { - /* documentation comment */ - char *str=(char*)line+3; - char *end; - while (*str<=' ' && *str!='\0') - str++; /* skip leading whitespace */ - if ((end=strrchr(str,'\n'))!=NULL) - *end='\0';/* erase trailing '\n' */ - /* if there is a disjunct block, we may need to attach the previous - * block to the global documentation - */ - if (!singleline && curfunc==NULL && get_docstring(0)!=NULL) - sc_attachdocumentation(NULL); - insert_docstring(str); - prev_singleline=TRUE; - } /* if */ - #endif - *line++='\n'; /* put "newline" at first slash */ - *line='\0'; /* put "zero-terminator" at second slash */ - } else { - if (*line=='\"' || *line=='\''){ /* leave literals unaltered */ - c=*line; /* ending quote, single or double */ - line+=1; - while ((*line!=c || *(line-1)==sc_ctrlchar) && *line!='\0') - line+=1; - line+=1; /* skip final quote */ - } else { - line+=1; - } /* if */ - } /* if */ - } /* if */ - } /* while */ - #if !defined SC_LIGHT - if (icomment==2) { - assert(commentidx0) - insert_docstring(comment); - } /* if */ - #endif -} - -/* btoi - * - * Attempts to interpret a numeric symbol as a boolean value. On success - * it returns the number of characters processed (so the line pointer can be - * adjusted) and the value is stored in "val". Otherwise it returns 0 and - * "val" is garbage. - * - * A boolean value must start with "0b" - */ -static int btoi(cell *val,const unsigned char *curptr) -{ - const unsigned char *ptr; - - *val=0; - ptr=curptr; - if (*ptr=='0' && *(ptr+1)=='b') { - ptr+=2; - while (*ptr=='0' || *ptr=='1' || *ptr=='_') { - if (*ptr!='_') - *val=(*val<<1) | (*ptr-'0'); - ptr++; - } /* while */ - } else { - return 0; - } /* if */ - if (alphanum(*ptr)) /* number must be delimited by non-alphanumeric char */ - return 0; - else - return (int)(ptr-curptr); -} - -/* dtoi - * - * Attempts to interpret a numeric symbol as a decimal value. On success - * it returns the number of characters processed and the value is stored in - * "val". Otherwise it returns 0 and "val" is garbage. - */ -static int dtoi(cell *val,const unsigned char *curptr) -{ - const unsigned char *ptr; - - *val=0; - ptr=curptr; - if (!isdigit(*ptr)) /* should start with digit */ - return 0; - while (isdigit(*ptr) || *ptr=='_') { - if (*ptr!='_') - *val=(*val*10)+(*ptr-'0'); - ptr++; - } /* while */ - if (alphanum(*ptr)) /* number must be delimited by non-alphanumerical */ - return 0; - if (*ptr=='.' && isdigit(*(ptr+1))) - return 0; /* but a fractional part must not be present */ - return (int)(ptr-curptr); -} - -/* htoi - * - * Attempts to interpret a numeric symbol as a hexadecimal value. On - * success it returns the number of characters processed and the value is - * stored in "val". Otherwise it return 0 and "val" is garbage. - */ -static int htoi(cell *val,const unsigned char *curptr) -{ - const unsigned char *ptr; - - *val=0; - ptr=curptr; - if (!isdigit(*ptr)) /* should start with digit */ - return 0; - if (*ptr=='0' && *(ptr+1)=='x') { /* C style hexadecimal notation */ - ptr+=2; - while (ishex(*ptr) || *ptr=='_') { - if (*ptr!='_') { - assert(ishex(*ptr)); - *val= *val<<4; - if (isdigit(*ptr)) - *val+= (*ptr-'0'); - else - *val+= (tolower(*ptr)-'a'+10); - } /* if */ - ptr++; - } /* while */ - } else { - return 0; - } /* if */ - if (alphanum(*ptr)) - return 0; - else - return (int)(ptr-curptr); -} - -/* ftoi - * - * Attempts to interpret a numeric symbol as a rational number, either as - * IEEE 754 single/double precision floating point or as a fixed point integer. - * On success it returns the number of characters processed and the value is - * stored in "val". Otherwise it returns 0 and "val" is unchanged. - * - * Pawn has stricter definition for rational numbers than most: - * o the value must start with a digit; ".5" is not a valid number, you - * should write "0.5" - * o a period must appear in the value, even if an exponent is given; "2e3" - * is not a valid number, you should write "2.0e3" - * o at least one digit must follow the period; "6." is not a valid number, - * you should write "6.0" - */ -static int ftoi(cell *val,const unsigned char *curptr) -{ - const unsigned char *ptr; - double fnum,ffrac,fmult; - unsigned long dnum,dbase; - int i, ignore; - - assert(rational_digits>=0 && rational_digits<9); - for (i=0,dbase=1; i0 && !ignore) { - error(222); /* number of digits exceeds rational number precision */ - ignore=TRUE; - } /* if */ - } /* if */ - ptr++; - } /* while */ - fnum += ffrac*fmult; /* form the number so far */ - if (*ptr=='e') { /* optional fractional part */ - int exp,sign; - ptr++; - if (*ptr=='-') { - sign=-1; - ptr++; - } else { - sign=1; - } /* if */ - if (!isdigit(*ptr)) /* 'e' should be followed by a digit */ - return 0; - exp=0; - while (isdigit(*ptr)) { - exp=(exp*10)+(*ptr-'0'); - ptr++; - } /* while */ -#if defined __GNUC__ - fmult=pow10(exp*sign); -#else - fmult=pow(10.0,exp*sign); -#endif - fnum *= fmult; - dnum *= (unsigned long)(fmult+0.5); - } /* if */ - - /* decide how to store the number */ - if (sc_rationaltag==0) { - error(70); /* rational number support was not enabled */ - *val=0; - } else if (rational_digits==0) { - /* floating point */ - #if PAWN_CELL_SIZE==32 - float value=(float)fnum; - *val=*((cell *)&value); - #if 0 /* SourceMod - not needed */ - /* I assume that the C/C++ compiler stores "float" values in IEEE 754 - * format (as mandated in the ANSI standard). Test this assumption - * anyway. - * Note: problems have been reported with GCC 3.2.x, version 3.3.x works. - */ - { float test1 = 0.0, test2 = 50.0, test3 = -50.0; - uint32_t bit = 1; - /* test 0.0 == all bits 0 */ - assert(*(uint32_t*)&test1==0x00000000L); - /* test sign & magnitude format */ - assert(((*(uint32_t*)&test2) ^ (*(uint32_t*)&test3)) == (bit << (PAWN_CELL_SIZE-1))); - /* test a known value */ - assert(*(uint32_t*)&test2==0x42480000L); - } - #endif - #elif PAWN_CELL_SIZE==64 - *val=*((cell *)&fnum); - #if 0 /* SourceMod - not needed */ - /* I assume that the C/C++ compiler stores "double" values in IEEE 754 - * format (as mandated in the ANSI standard). - */ - { float test1 = 0.0, test2 = 50.0, test3 = -50.0; - uint64_t bit = 1; - /* test 0.0 == all bits 0 */ - assert(*(uint64_t*)&test1==0x00000000L); - /* test sign & magnitude format */ - assert(((*(uint64_t*)&test2) ^ (*(uint64_t*)&test3)) == (bit << (PAWN_CELL_SIZE-1))); - } - #endif - #else - #error Unsupported cell size - #endif - } else { - /* fixed point */ - *val=(cell)dnum; - } /* if */ - - return (int)(ptr-curptr); -} - -/* number - * - * Reads in a number (binary, decimal or hexadecimal). It returns the number - * of characters processed or 0 if the symbol couldn't be interpreted as a - * number (in this case the argument "val" remains unchanged). This routine - * relies on the 'early dropout' implementation of the logical or (||) - * operator. - * - * Note: the routine doesn't check for a sign (+ or -). The - is checked - * for at "hier2()" (in fact, it is viewed as an operator, not as a - * sign) and the + is invalid (as in K&R C, and unlike ANSI C). - */ -static int number(cell *val,const unsigned char *curptr) -{ - int i; - cell value; - - if ((i=btoi(&value,curptr))!=0 /* binary? */ - || (i=htoi(&value,curptr))!=0 /* hexadecimal? */ - || (i=dtoi(&value,curptr))!=0) /* decimal? */ - { - *val=value; - return i; - } else { - return 0; /* else not a number */ - } /* if */ -} - -static void chrcat(char *str,char chr) -{ - str=strchr(str,'\0'); - *str++=chr; - *str='\0'; -} - -static int preproc_expr(cell *val,int *tag) -{ - int result; - int index; - cell code_index; - char *term; - - /* Disable staging; it should be disabled already because - * expressions may not be cut off half-way between conditional - * compilations. Reset the staging index, but keep the code - * index. - */ - if (stgget(&index,&code_index)) { - error(57); /* unfinished expression */ - stgdel(0,code_index); - stgset(FALSE); - } /* if */ - assert((lptr-pline)<(int)strlen((char*)pline)); /* lptr must point inside the string */ - #if !defined NO_DEFINE - /* preprocess the string */ - substallpatterns(pline,sLINEMAX); - assert((lptr-pline)<(int)strlen((char*)pline)); /* lptr must STILL point inside the string */ - #endif - /* append a special symbol to the string, so the expression - * analyzer won't try to read a next line when it encounters - * an end-of-line - */ - assert(strlen((char*)pline)=0); - if (iflevel>=sCOMP_STACK) - error(FATAL_ERROR_ALLOC_OVERFLOW,"Conditional compilation stack"); - iflevel++; - if (SKIPPING) - break; /* break out of switch */ - skiplevel=iflevel; - preproc_expr(&val,NULL); /* get value (or 0 on error) */ - ifstack[iflevel-1]=(char)(val ? PARSEMODE : SKIPMODE); - check_empty(lptr); - break; - case tpELSE: - case tpELSEIF: - ret=CMD_IF; - assert(iflevel>=0); - if (iflevel==0) { - error(26); /* no matching #if */ - errorset(sRESET,0); - } else { - /* check for earlier #else */ - if ((ifstack[iflevel-1] & HANDLED_ELSE)==HANDLED_ELSE) { - if (tok==tpELSEIF) - error(61); /* #elseif directive may not follow an #else */ - else - error(60); /* multiple #else directives between #if ... #endif */ - errorset(sRESET,0); - } else { - assert(iflevel>0); - /* if there has been a "parse mode" on this level, set "skip mode", - * otherwise, clear "skip mode" - */ - if ((ifstack[iflevel-1] & PARSEMODE)==PARSEMODE) { - /* there has been a parse mode already on this level, so skip the rest */ - ifstack[iflevel-1] |= (char)SKIPMODE; - /* if we were already skipping this section, allow expressions with - * undefined symbols; otherwise check the expression to catch errors - */ - if (tok==tpELSEIF) { - if (skiplevel==iflevel) - preproc_expr(&val,NULL); /* get, but ignore the expression */ - else - lptr=(unsigned char*)strchr((char*)lptr,'\0'); - } /* if */ - } else { - /* previous conditions were all FALSE */ - if (tok==tpELSEIF) { - /* if we were already skipping this section, allow expressions with - * undefined symbols; otherwise check the expression to catch errors - */ - if (skiplevel==iflevel) { - preproc_expr(&val,NULL); /* get value (or 0 on error) */ - } else { - lptr=(unsigned char*)strchr((char*)lptr,'\0'); - val=0; - } /* if */ - ifstack[iflevel-1]=(char)(val ? PARSEMODE : SKIPMODE); - } else { - /* a simple #else, clear skip mode */ - ifstack[iflevel-1] &= (char)~SKIPMODE; - } /* if */ - } /* if */ - } /* if */ - } /* if */ - check_empty(lptr); - break; - case tpENDIF: - ret=CMD_IF; - if (iflevel==0){ - error(26); /* no matching "#if" */ - errorset(sRESET,0); - } else { - iflevel--; - if (iflevel0) { - free(inpfname); - inpfname=duplicatestring(pathname); - if (inpfname==NULL) - error(FATAL_ERROR_OOM); - fline=0; - } /* if */ - } /* if */ - check_empty(lptr); - break; - case tpLINE: - if (!SKIPPING) { - if (lex(&val,&str)!=tNUMBER) - error(8); /* invalid/non-constant expression */ - fline=(int)val; - } /* if */ - check_empty(lptr); - break; - case tpASSERT: - if (!SKIPPING && (sc_debug & sCHKBOUNDS)!=0) { - for (str=(char*)lptr; *str<=' ' && *str!='\0'; str++) - /* nothing */; /* save start of expression */ - preproc_expr(&val,NULL); /* get constant expression (or 0 on error) */ - if (!val) - error(170,str); /* assertion failed */ - check_empty(lptr); - } /* if */ - break; - case tpPRAGMA: - if (!SKIPPING) { - if (lex(&val,&str)==tSYMBOL) { - if (strcmp(str,"amxlimit")==0) { - preproc_expr(&pc_amxlimit,NULL); - } else if (strcmp(str,"amxram")==0) { - preproc_expr(&pc_amxram,NULL); - } else if (strcmp(str,"codepage")==0) { - char name[sNAMEMAX+1]; - while (*lptr<=' ' && *lptr!='\0') - lptr++; - if (*lptr=='"') { - lptr=getstring((unsigned char*)name,sizeof name,lptr); - } else { - size_t i; - for (i=0; i9) { - error(68); /* invalid rational number precision */ - digits=0; - } /* if */ - if (*lptr==')') - lptr++; - } /* if */ - /* add the tag (make it public) and check the values */ - int tag=pc_addtag(name); - if (sc_rationaltag==0 || (sc_rationaltag==tag && rational_digits==(int)digits)) { - sc_rationaltag=tag; - rational_digits=(int)digits; - } else { - error(69); /* rational number format already set, can only be set once */ - } /* if */ - } else if (strcmp(str,"semicolon")==0) { - cell val; - preproc_expr(&val,NULL); - sc_needsemicolon=(int)val; - } else if (strcmp(str, "newdecls")==0) { - while (*lptr<=' ' && *lptr!='\0') - lptr++; - if (strncmp((char *)lptr, "required", 8) == 0) - sc_require_newdecls = 1; - else if (strncmp((char *)lptr, "optional", 8) == 0) - sc_require_newdecls = 0; - else - error(146); - lptr=(unsigned char*)strchr((char*)lptr,'\0'); /* skip to end (ignore "extra characters on line") */ - } else if (strcmp(str,"tabsize")==0) { - cell val; - preproc_expr(&val,NULL); - sc_tabsize=(int)val; - } else if (strcmp(str,"align")==0) { - sc_alignnext=TRUE; - } else if (strcmp(str,"unused")==0) { - char name[sNAMEMAX+1]; - size_t i; - int comma; - symbol *sym; - do { - /* get the name */ - while (*lptr<=' ' && *lptr!='\0') - lptr++; - for (i=0; iusage |= uREAD; - if (sym->ident==iVARIABLE || sym->ident==iREFERENCE - || sym->ident==iARRAY || sym->ident==iREFARRAY) - sym->usage |= uWRITTEN; - } else { - error(17,name); /* undefined symbol */ - } /* if */ - /* see if a comma follows the name */ - while (*lptr<=' ' && *lptr!='\0') - lptr++; - comma= (*lptr==','); - if (comma) - lptr++; - } while (comma); - } else { - error(207); /* unknown #pragma */ - } /* if */ - } else { - error(207); /* unknown #pragma */ - } /* if */ - check_empty(lptr); - } /* if */ - break; - case tpENDINPUT: - case tpENDSCRPT: - if (!SKIPPING) { - check_empty(lptr); - assert(inpf!=NULL); - if (inpf!=inpf_org) - pc_closesrc(inpf); - inpf=NULL; - } /* if */ - break; -#if !defined NO_DEFINE - case tpDEFINE: { - ret=CMD_DEFINE; - if (!SKIPPING) { - char *pattern,*substitution; - const unsigned char *start,*end; - int count,prefixlen; - stringpair *def; - /* find the pattern to match */ - while (*lptr<=' ' && *lptr!='\0') - lptr++; - start=lptr; /* save starting point of the match pattern */ - count=0; - while (*lptr>' ' && *lptr!='\0') { - litchar(&lptr,0); /* litchar() advances "lptr" and handles escape characters */ - count++; - } /* while */ - end=lptr; - /* check pattern to match */ - if (!alpha(*start)) { - error(74); /* pattern must start with an alphabetic character */ - break; - } /* if */ - /* store matched pattern */ - pattern=(char*)malloc(count+1); - if (pattern==NULL) - error(FATAL_ERROR_OOM); - lptr=start; - count=0; - while (lptr!=end) { - assert(lptr=2 && isdigit(pattern[count-1]) && pattern[count-2]=='%') - pattern[count-2]='\0'; - /* find substitution string */ - while (*lptr<=' ' && *lptr!='\0') - lptr++; - start=lptr; /* save starting point of the match pattern */ - count=0; - end=NULL; - while (*lptr!='\0') { - /* keep position of the start of trailing whitespace */ - if (*lptr<=' ') { - if (end==NULL) - end=lptr; - } else { - end=NULL; - } /* if */ - count++; - lptr++; - } /* while */ - if (end==NULL) - end=lptr; - /* store matched substitution */ - substitution=(char*)malloc(count+1); /* +1 for '\0' */ - if (substitution==NULL) - error(FATAL_ERROR_OOM); - lptr=start; - count=0; - while (lptr!=end) { - assert(lptr0); - if ((def=find_subst(pattern,prefixlen))!=NULL) { - if (strcmp(def->first,pattern)!=0 || strcmp(def->second,substitution)!=0) - error(201,pattern); /* redefinition of macro (non-identical) */ - delete_subst(pattern,prefixlen); - } /* if */ - /* add the pattern/substitution pair to the list */ - assert(strlen(pattern)>0); - insert_subst(pattern,substitution,prefixlen); - free(pattern); - free(substitution); - } /* if */ - break; - } /* case */ - case tpUNDEF: - if (!SKIPPING) { - if (lex(&val,&str)==tSYMBOL) { - ret=delete_subst(str,strlen(str)); - if (!ret) { - /* also undefine normal constants */ - symbol *sym=findconst(str,NULL); - if (sym!=NULL && (sym->usage & (uENUMROOT | uENUMFIELD))==0) { - delete_symbol(&glbtab,sym); - ret=TRUE; - } /* if */ - } /* if */ - if (!ret) - error(17,str); /* undefined symbol */ - } else { - error(20,str); /* invalid symbol name */ - } /* if */ - check_empty(lptr); - } /* if */ - break; -#endif - case tpERROR: - while (*lptr<=' ' && *lptr!='\0') - lptr++; - if (!SKIPPING) - error(171,lptr); /* user error */ - break; - default: - error(31); /* unknown compiler directive */ - ret=SKIPPING ? CMD_CONDFALSE : CMD_NONE; /* process as normal line */ - } /* switch */ - return ret; -} - -#if !defined NO_DEFINE -static int is_startstring(const unsigned char *string) -{ - if (*string=='\"' || *string=='\'') - return TRUE; /* "..." */ - - if (*string=='!') { - string++; - if (*string=='\"' || *string=='\'') - return TRUE; /* !"..." */ - if (*string==sc_ctrlchar) { - string++; - if (*string=='\"' || *string=='\'') - return TRUE; /* !\"..." */ - } /* if */ - } else if (*string==sc_ctrlchar) { - string++; - if (*string=='\"' || *string=='\'') - return TRUE; /* \"..." */ - if (*string=='!') { - string++; - if (*string=='\"' || *string=='\'') - return TRUE; /* \!"..." */ - } /* if */ - } /* if */ - - return FALSE; -} - -static const unsigned char *skipstring(const unsigned char *string) -{ - char endquote; - int flags=0; - - while (*string=='!' || *string==sc_ctrlchar) { - if (*string==sc_ctrlchar) - flags=RAWMODE; - string++; - } /* while */ - - endquote=*string; - assert(endquote=='"' || endquote=='\''); - string++; /* skip open quote */ - while (*string!=endquote && *string!='\0') - litchar(&string,flags); - return string; -} - -static const unsigned char *skippgroup(const unsigned char *string) -{ - int nest=0; - char open=*string; - char close; - - switch (open) { - case '(': - close=')'; - break; - case '{': - close='}'; - break; - case '[': - close=']'; - break; - case '<': - close='>'; - break; - default: - assert(0); - close='\0'; /* only to avoid a compiler warning */ - }/* switch */ - - string++; - while (*string!=close || nest>0) { - if (*string==open) - nest++; - else if (*string==close) - nest--; - else if (is_startstring(string)) - string=skipstring(string); - if (*string=='\0') - break; - string++; - } /* while */ - return string; -} - -static char *strdel(char *str,size_t len) -{ - size_t length=strlen(str); - if (len>length) - len=length; - memmove(str, str+len, length-len+1); /* include EOS byte */ - return str; -} - -static char *strins(char *dest,const char *src,size_t srclen) -{ - size_t destlen=strlen(dest); - assert(srclen<=strlen(src)); - memmove(dest+srclen, dest, destlen+1);/* include EOS byte */ - memcpy(dest, src, srclen); - return dest; -} - -static int substpattern(unsigned char *line,size_t buffersize,char *pattern,char *substitution) -{ - int prefixlen; - const unsigned char *p,*s,*e; - unsigned char *args[10]; - int match,arg,len,argsnum=0; - int stringize; - - memset(args,0,sizeof args); - - /* check the length of the prefix */ - for (prefixlen=0,s=(unsigned char*)pattern; alphanum(*s); prefixlen++,s++) - /* nothing */; - assert(prefixlen>0); - assert(strncmp((char*)line,pattern,prefixlen)==0); - - /* pattern prefix matches; match the rest of the pattern, gather - * the parameters - */ - s=line+prefixlen; - p=(unsigned char*)pattern+prefixlen; - match=TRUE; /* so far, pattern matches */ - while (match && *s!='\0' && *p!='\0') { - if (*p=='%') { - p++; /* skip '%' */ - if (isdigit(*p)) { - arg=*p-'0'; - assert(arg>=0 && arg<=9); - p++; /* skip parameter id */ - assert(*p!='\0'); - /* match the source string up to the character after the digit - * (skipping strings in the process - */ - e=s; - while (*e!=*p && *e!='\0' && *e!='\n') { - if (is_startstring(e)) /* skip strings */ - e=skipstring(e); - else if (strchr("({[",*e)!=NULL) /* skip parenthized groups */ - e=skippgroup(e); - if (*e!='\0') - e++; /* skip non-alphapetic character (or closing quote of - * a string, or the closing paranthese of a group) */ - } /* while */ - /* store the parameter (overrule any earlier) */ - if (args[arg]!=NULL) - free(args[arg]); - else - argsnum++; - len=(int)(e-s); - args[arg]=(unsigned char*)malloc(len+1); - if (args[arg]==NULL) - error(FATAL_ERROR_OOM); - strlcpy((char*)args[arg],(char*)s,len+1); - /* character behind the pattern was matched too */ - if (*e==*p) { - s=e+1; - } else if (*e=='\n' && *p==';' && *(p+1)=='\0' && !sc_needsemicolon) { - s=e; /* allow a trailing ; in the pattern match to end of line */ - } else { - assert(*e=='\0' || *e=='\n'); - match=FALSE; - s=e; - } /* if */ - p++; - } else { - match=FALSE; - } /* if */ - } else if (*p==';' && *(p+1)=='\0' && !sc_needsemicolon) { - /* source may be ';' or end of the line */ - while (*s<=' ' && *s!='\0') - s++; /* skip white space */ - if (*s!=';' && *s!='\0') - match=FALSE; - p++; /* skip the semicolon in the pattern */ - } else { - cell ch; - /* skip whitespace between two non-alphanumeric characters, except - * for two identical symbols - */ - assert((char*)p>pattern); - if (!alphanum(*p) && *(p-1)!=*p) - while (*s<=' ' && *s!='\0') - s++; /* skip white space */ - ch=litchar(&p,0); /* this increments "p" */ - if (*s!=ch) - match=FALSE; - else - s++; /* this character matches */ - } /* if */ - } /* while */ - - if (match && *p=='\0') { - /* if the last character to match is an alphanumeric character, the - * current character in the source may not be alphanumeric - */ - assert(p>(unsigned char*)pattern); - if (alphanum(*(p-1)) && alphanum(*s)) - match=FALSE; - } /* if */ - - if (match) { - /* calculate the length of the substituted string */ - for (e=(unsigned char*)substitution,len=0; *e!='\0'; e++) { - if(*e=='#' && *(e+1)=='%' && isdigit(*(e+2)) && argsnum) { - stringize=1; - e++; /* skip '#' */ - } else { - stringize=0; - } /* if */ - if (*e=='%' && isdigit(*(e+1)) && argsnum) { - arg=*(e+1)-'0'; - assert(arg>=0 && arg<=9); - assert(stringize==0 || stringize==1); - if (args[arg]!=NULL) { - len+=strlen((char*)args[arg])+2*stringize; - e++; - } else { - len++; - } - } else { - len++; - } /* if */ - } /* for */ - /* check length of the string after substitution */ - if (strlen((char*)line) + len - (int)(s-line) > buffersize) { - error(75); /* line too long */ - } else { - /* substitute pattern */ - strdel((char*)line,(int)(s-line)); - for (e=(unsigned char*)substitution,s=line; *e!='\0'; e++) { - if (*e=='#' && *(e+1)=='%' && isdigit(*(e+2))) { - stringize=1; - e++; /* skip '#' */ - } else { - stringize=0; - } /* if */ - if (*e=='%' && isdigit(*(e+1))) { - arg=*(e+1)-'0'; - assert(arg>=0 && arg<=9); - if (args[arg]!=NULL) { - if (stringize) - strins((char*)s++,"\"",1); - strins((char*)s,(char*)args[arg],strlen((char*)args[arg])); - s+=strlen((char*)args[arg]); - if (stringize) - strins((char*)s++,"\"",1); - } else { - error(236); /* parameter does not exist, incorrect #define pattern */ - strins((char*)s,(char*)e,2); - s+=2; - } /* if */ - e++; /* skip %, digit is skipped later */ - } else if (*e == '"') { - p=e; - if (is_startstring(e)) { - e=skipstring(e); - strins((char*)s,(char *)p,(e-p+1)); - s+=(e-p+1); - } else { - strins((char*)s,(char*)e,1); - s++; - } - } else { - strins((char*)s,(char*)e,1); - s++; - } /* if */ - } /* for */ - } /* if */ - } /* if */ - - for (arg=0; arg<10; arg++) - if (args[arg]!=NULL) - free(args[arg]); - - return match; -} - -static void substallpatterns(unsigned char *line,int buffersize) -{ - unsigned char *start, *end; - int prefixlen; - stringpair *subst; - - start=line; - while (*start!='\0') { - /* find the start of a prefix (skip all non-alphabetic characters), - * also skip strings - */ - while (!alpha(*start) && *start!='\0') { - /* skip strings */ - if (is_startstring(start)) { - start=(unsigned char *)skipstring(start); - if (*start=='\0') - break; /* abort loop on error */ - } /* if */ - start++; /* skip non-alphapetic character (or closing quote of a string) */ - } /* while */ - if (*start=='\0') - break; /* abort loop on error */ - /* if matching the operator "defined", skip it plus the symbol behind it */ - if (strncmp((char*)start,"defined",7)==0 && !isalpha((char)*(start+7))) { - start+=7; /* skip "defined" */ - /* skip white space & parantheses */ - while ((*start<=' ' && *start!='\0') || *start=='(') - start++; - /* skip the symbol behind it */ - while (alphanum(*start)) - start++; - /* drop back into the main loop */ - continue; - } /* if */ - /* get the prefix (length), look for a matching definition */ - prefixlen=0; - end=start; - while (alphanum(*end)) { - prefixlen++; - end++; - } /* while */ - assert(prefixlen>0); - subst=find_subst((char*)start,prefixlen); - if (subst!=NULL) { - /* properly match the pattern and substitute */ - if (!substpattern(start,buffersize-(int)(start-line),subst->first,subst->second)) - start=end; /* match failed, skip this prefix */ - /* match succeeded: do not update "start", because the substitution text - * may be matched by other macros - */ - } else { - start=end; /* no macro with this prefix, skip this prefix */ - } /* if */ - } /* while */ -} -#endif - -/* scanellipsis - * Look for ... in the string and (if not there) in the remainder of the file, - * but restore (or keep intact): - * - the current position in the file - * - the comment parsing state - * - the line buffer used by the lexical analyser - * - the active line number and the active file - * - * The function returns 1 if an ellipsis was found and 0 if not - */ -static int scanellipsis(const unsigned char *lptr) -{ - static void *inpfmark=NULL; - unsigned char *localbuf; - short localcomment,found; - - /* first look for the ellipsis in the remainder of the string */ - while (*lptr<=' ' && *lptr!='\0') - lptr++; - if (lptr[0]=='.' && lptr[1]=='.' && lptr[2]=='.') - return 1; - if (*lptr!='\0') - return 0; /* stumbled on something that is not an ellipsis and not white-space */ - - /* the ellipsis was not on the active line, read more lines from the current - * file (but save its position first) - */ - if (inpf==NULL || pc_eofsrc(inpf)) - return 0; /* quick exit: cannot read after EOF */ - if ((localbuf=(unsigned char*)malloc((sLINEMAX+1)*sizeof(unsigned char)))==NULL) - return 0; - inpfmark=pc_getpossrc(inpf,inpfmark); - localcomment=icomment; - - found=0; - /* read from the file, skip preprocessing, but strip off comments */ - while (!found && pc_readsrc(inpf,localbuf,sLINEMAX)!=NULL) { - stripcom(localbuf); - lptr=localbuf; - /* skip white space */ - while (*lptr<=' ' && *lptr!='\0') - lptr++; - if (lptr[0]=='.' && lptr[1]=='.' && lptr[2]=='.') - found=1; - else if (*lptr!='\0') - break; /* stumbled on something that is not an ellipsis and not white-space */ - } /* while */ - - /* clean up & reset */ - free(localbuf); - pc_resetsrc(inpf,inpfmark); - icomment=localcomment; - return found; -} - -/* preprocess - * - * Reads a line by readline() into "pline" and performs basic preprocessing: - * deleting comments, skipping lines with false "#if.." code and recognizing - * other compiler directives. There is an indirect recursion: lex() calls - * preprocess() if a new line must be read, preprocess() calls command(), - * which at his turn calls lex() to identify the token. - * - * Global references: lptr (altered) - * pline (altered) - * freading (referred to only) - */ -void preprocess(void) -{ - int iscommand; - - if (!freading) - return; - do { - readline(pline); - stripcom(pline); /* ??? no need for this when reading back from list file (in the second pass) */ - lptr=pline; /* set "line pointer" to start of the parsing buffer */ - iscommand=command(); - if (iscommand!=CMD_NONE) - errorset(sRESET,0); /* reset error flag ("panic mode") on empty line or directive */ - #if !defined NO_DEFINE - if (iscommand==CMD_NONE) { - assert(lptr!=term_expr); - substallpatterns(pline,sLINEMAX); - lptr=pline; /* reset "line pointer" to start of the parsing buffer */ - } /* if */ - #endif - if (sc_status==statFIRST && sc_listing && freading - && (iscommand==CMD_NONE || iscommand==CMD_EMPTYLINE || iscommand==CMD_DIRECTIVE)) - { - listline++; - if (fline!=listline) { - listline=fline; - setlinedirect(fline); - } /* if */ - if (iscommand==CMD_EMPTYLINE) - pc_writeasm(outf,"\n"); - else - pc_writeasm(outf,(char*)pline); - } /* if */ - } while (iscommand!=CMD_NONE && iscommand!=CMD_TERM && freading); /* enddo */ -} - -static const unsigned char *unpackedstring(const unsigned char *lptr,int flags) -{ - while (*lptr!='\"' && *lptr!='\0') { - if (*lptr=='\a') { /* ignore '\a' (which was inserted at a line concatenation) */ - lptr++; - continue; - } /* if */ - litadd(litchar(&lptr,flags | UTF8MODE)); /* litchar() alters "lptr" */ - } /* while */ - litadd(0); /* terminate string */ - return lptr; -} - -static const unsigned char *packedstring(const unsigned char *lptr,int flags) -{ - int i; - ucell val,c; - - i=0; /* start at least significant byte */ - val=0; - glbstringread=1; - while (*lptr!='\"' && *lptr!='\0') { - if (*lptr=='\a') { /* ignore '\a' (which was inserted at a line concatenation) */ - lptr++; - continue; - } /* if */ - c=litchar(&lptr,flags); /* litchar() alters "lptr" */ - if (c>=(ucell)(1 << sCHARBITS)) - error(43); /* character constant exceeds range */ - val |= (c << 8*i); - glbstringread++; - if (i==sizeof(ucell)-(sCHARBITS/8)) { - litadd(val); - val=0; - i=0; - } else { - i=i+1; - } - } /* if */ - /* save last code; make sure there is at least one terminating zero character */ - if (i!=0) - litadd(val); /* at least one zero character in "val" */ - else - litadd(0); /* add full cell of zeros */ - return lptr; -} - -/* lex(lexvalue,lexsym) Lexical Analysis - * - * lex() first deletes leading white space, then checks for multi-character - * operators, keywords (including most compiler directives), numbers, - * labels, symbols and literals (literal characters are converted to a number - * and are returned as such). If every check fails, the line must contain - * a single-character operator. So, lex() returns this character. In the other - * case (something did match), lex() returns the number of the token. All - * these tokens have been assigned numbers above 255. - * - * Some tokens have "attributes": - * tNUMBER the value of the number is return in "lexvalue". - * tRATIONAL the value is in IEEE 754 encoding or in fixed point - * encoding in "lexvalue". - * tSYMBOL the first sNAMEMAX characters of the symbol are - * stored in a buffer, a pointer to this buffer is - * returned in "lexsym". - * tLABEL the first sNAMEMAX characters of the label are - * stored in a buffer, a pointer to this buffer is - * returned in "lexsym". - * tSTRING the string is stored in the literal pool, the index - * in the literal pool to this string is stored in - * "lexvalue". - * - * lex() stores all information (the token found and possibly its attribute) - * in global variables. This allows a token to be examined twice. If "_pushed" - * is true, this information is returned. - * - * Global references: lptr (altered) - * fline (referred to only) - * litidx (referred to only) - * _pushed - */ - -static int _lexnewline; - -// lex() is called recursively, which messes up the lookahead buffer. To get -// around this we use two separate token buffers. -token_buffer_t sNormalBuffer; -token_buffer_t sPreprocessBuffer; -token_buffer_t *sTokenBuffer; - -static full_token_t *current_token() -{ - return &sTokenBuffer->tokens[sTokenBuffer->cursor]; -} - -static full_token_t *next_token() -{ - assert(sTokenBuffer->depth > 0); - int cursor = sTokenBuffer->cursor + 1; - if (cursor == MAX_TOKEN_DEPTH) - cursor = 0; - return &sTokenBuffer->tokens[cursor]; -} - -void lexinit(void) -{ - stkidx=0; /* index for pushstk() and popstk() */ - iflevel=0; /* preprocessor: nesting of "#if" is currently 0 */ - skiplevel=0; /* preprocessor: not currently skipping */ - icomment=0; /* currently not in a multiline comment */ - _lexnewline=FALSE; - memset(&sNormalBuffer, 0, sizeof(sNormalBuffer)); - memset(&sPreprocessBuffer, 0, sizeof(sPreprocessBuffer)); - sTokenBuffer = &sNormalBuffer; -} - -const char *sc_tokens[] = { - "*=", "/=", "%=", "+=", "-=", "<<=", ">>>=", ">>=", "&=", "^=", "|=", - "||", "&&", "==", "!=", "<=", ">=", "<<", ">>>", ">>", "++", "--", - "...", "..", "::", - "acquire", - "as", - "assert", - "*begin", - "break", - "builtin", - "catch", - "case", - "cast_to", - "cellsof", - "char", - "const", - "continue", - "decl", - "default", - "defined", - "delete", - "do", - "double", - "else", - "*end", - "enum", - "exit", - "explicit", - "finally", - "for", - "foreach", - "forward", - "funcenum", - "functag", - "function", - "goto", - "if", - "implicit", - "import", - "in", - "int", - "int8", - "int16", - "int32", - "int64", - "interface", - "intn", - "let", - "methodmap", - "namespace", - "native", - "new", - "null", - "__nullable__", - "object", - "operator", - "package", - "private", - "protected", - "public", - "readonly", - "return", - "sealed", - "sizeof", - "sleep", - "static", - "stock", - "struct", - "switch", - "tagof", - "*then", - "this", - "throw", - "try", - "typedef", - "typeof", - "typeset", - "uint8", - "uint16", - "uint32", - "uint64", - "uintn", - "union", - "using", - "var", - "variant", - "view_as", - "virtual", - "void", - "volatile", - "while", - "with", - "#assert", "#define", "#else", "#elseif", "#endif", "#endinput", - "#endscript", "#error", "#file", "#if", "#include", "#line", "#pragma", - "#tryinclude", "#undef", - ";", ";", "-integer value-", "-rational value-", "-identifier-", - "-label-", "-string-", "-string-" -}; - -static inline bool -IsUnimplementedKeyword(int token) -{ - switch (token) { - case tACQUIRE: - case tAS: - case tCATCH: - case tCAST_TO: - case tDOUBLE: - case tEXPLICIT: - case tFINALLY: - case tFOREACH: - case tIMPLICIT: - case tIMPORT: - case tIN: - case tINT8: - case tINT16: - case tINT32: - case tINT64: - case tINTERFACE: - case tINTN: - case tLET: - case tNAMESPACE: - case tPACKAGE: - case tPRIVATE: - case tPROTECTED: - case tREADONLY: - case tSEALED: - case tTHROW: - case tTRY: - case tTYPEOF: - case tUINT8: - case tUINT16: - case tUINT32: - case tUINT64: - case tUINTN: - case tUNION: - case tUSING: - case tVAR: - case tVARIANT: - case tVIRTUAL: - case tVOLATILE: - case tWITH: - return true; - default: - return false; - } -} - -static full_token_t *advance_token_ptr() -{ - assert(sTokenBuffer->depth == 0); - sTokenBuffer->num_tokens++; - sTokenBuffer->cursor++; - if (sTokenBuffer->cursor == MAX_TOKEN_DEPTH) - sTokenBuffer->cursor = 0; - - return current_token(); -} - -static void preprocess_in_lex() -{ - sTokenBuffer = &sPreprocessBuffer; - preprocess(); - sTokenBuffer = &sNormalBuffer; -} - -// Pops a token off the token buffer, making it the current token. -static void lexpop() -{ - assert(sTokenBuffer->depth > 0); - - sTokenBuffer->depth--; - sTokenBuffer->cursor++; - if (sTokenBuffer->cursor == MAX_TOKEN_DEPTH) - sTokenBuffer->cursor = 0; -} - -int lex(cell *lexvalue,char **lexsym) -{ - int i,toolong,newline; - const unsigned char *starttoken; - - if (sTokenBuffer->depth > 0) { - lexpop(); - *lexvalue = current_token()->value; - *lexsym = current_token()->str; - return current_token()->id; - } - - full_token_t *tok = advance_token_ptr(); - tok->id = 0; - tok->value = 0; - tok->str[0] = '\0'; - tok->len = 0; - - *lexvalue = tok->value; - *lexsym = tok->str; - - _lexnewline=FALSE; - if (!freading) - return 0; - - newline= (lptr==pline); /* does lptr point to start of line buffer */ - while (*lptr<=' ') { /* delete leading white space */ - if (*lptr=='\0') { - preprocess_in_lex(); - if (!freading) - return 0; - if (lptr==term_expr) /* special sequence to terminate a pending expression */ - return (tok->id = tENDEXPR); - _lexnewline=TRUE; /* set this after preprocess(), because - * preprocess() calls lex() recursively */ - newline=TRUE; - } else { - lptr+=1; - } /* if */ - } /* while */ - if (newline) { - stmtindent=0; - for (i=0; i<(int)(lptr-pline); i++) - if (pline[i]=='\t' && sc_tabsize>0) - stmtindent += (int)(sc_tabsize - (stmtindent+sc_tabsize) % sc_tabsize); - else - stmtindent++; - } /* if */ - - tok->start.line = fline; - tok->start.col = (int)(lptr - pline); - - i=tFIRST; - const char **tokptr=sc_tokens; - while (i<=tMIDDLE) { /* match multi-character operators */ - if (*lptr==**tokptr && match(*tokptr,FALSE)) { - tok->id = i; - if (pc_docexpr) /* optionally concatenate to documentation string */ - insert_autolist(*tokptr); - tok->end.line = fline; - tok->end.col = (int)(lptr - pline); - return tok->id; - } /* if */ - i+=1; - tokptr+=1; - } /* while */ - while (i<=tLAST) { /* match reserved words and compiler directives */ - if (*lptr==**tokptr && match(*tokptr,TRUE)) { - if (IsUnimplementedKeyword(i)) { - // Try to gracefully error. - error(173, sc_tokens[i - tFIRST]); - tok->id = tSYMBOL; - strcpy(tok->str, sc_tokens[i - tFIRST]); - tok->len = strlen(tok->str); - } else if (*lptr == ':' && - (i == tINT || - i == tVOID)) - { - // Special case 'int:' to its old behavior: an implicit view_as<> cast - // with Pawn's awful lowercase coercion semantics. - const char *token = sc_tokens[i - tFIRST]; - switch (i) { - case tINT: - error(238, token, token); - break; - case tVOID: - error(239, token, token); - break; - } - lptr++; - tok->id = tLABEL; - strcpy(tok->str, token); - tok->len = strlen(tok->str); - } else { - tok->id = i; - errorset(sRESET,0); /* reset error flag (clear the "panic mode")*/ - if (pc_docexpr) /* optionally concatenate to documentation string */ - insert_autolist(*tokptr); - } - tok->end.line = fline; - tok->end.col = (int)(lptr - pline); - return tok->id; - } /* if */ - i+=1; - tokptr+=1; - } /* while */ - - starttoken=lptr; /* save start pointer (for concatenating to documentation string) */ - if ((i=number(&tok->value, lptr))!=0) { /* number */ - tok->id = tNUMBER; - *lexvalue = tok->value; - lptr+=i; - } else if ((i=ftoi(&tok->value, lptr))!=0) { - tok->id = tRATIONAL; - *lexvalue = tok->value; - lptr+=i; - } else if (alpha(*lptr)) { /* symbol or label */ - /* Note: only sNAMEMAX characters are significant. The compiler - * generates a warning if a symbol exceeds this length. - */ - tok->id = tSYMBOL; - i=0; - toolong=0; - while (alphanum(*lptr)){ - tok->str[i]=*lptr; - lptr+=1; - if (istr[i]='\0'; - tok->len = i; - if (toolong) { - /* symbol too long, truncated to sNAMEMAX chars */ - error(200, tok->str, sNAMEMAX); - } - if (tok->str[0]==PUBLIC_CHAR && tok->str[1]=='\0') { - tok->id = PUBLIC_CHAR; /* '@' all alone is not a symbol, it is an operator */ - } else if (tok->str[0]=='_' && tok->str[1]=='\0') { - tok->id = '_'; /* '_' by itself is not a symbol, it is a placeholder */ - } /* if */ - if (*lptr==':' && *(lptr+1)!=':' && tok->id != PUBLIC_CHAR) { - if (sc_allowtags) { - tok->id = tLABEL; /* it wasn't a normal symbol, it was a label/tagname */ - lptr+=1; /* skip colon */ - } else if (find_constval(&tagname_tab,tok->str,0)!=NULL) { - /* this looks like a tag override (because a tag with this name - * exists), but tags are not allowed right now, so it is probably an - * error - */ - error(220); - } /* if */ - } /* if */ - } else if (*lptr=='\"' /* unpacked string literal */ -#if 0 - || (*lptr==sc_ctrlchar && *(lptr+1)=='\"') /* unpacked raw string */ - || (*lptr=='!' && *(lptr+1)=='\"') /* packed string */ - || (*lptr=='!' && *(lptr+1)==sc_ctrlchar && *(lptr+2)=='\"') /* packed raw string */ - || (*lptr==sc_ctrlchar && *(lptr+1)=='!' && *(lptr+2)=='\"') /* packed raw string */ -#endif - ) - { - if (sLiteralQueueDisabled) { - tok->id = tPENDING_STRING; - tok->end = tok->start; - return tok->id; - } - int stringflags,segmentflags; - char *cat; - tok->id = tSTRING; - *lexvalue = tok->value = litidx; - tok->str[0]='\0'; - stringflags=-1; /* to mark the first segment */ - for ( ;; ) { - if(*lptr=='!') - segmentflags= (*(lptr+1)==sc_ctrlchar) ? RAWMODE | ISPACKED : ISPACKED; - else if (*lptr==sc_ctrlchar) - segmentflags= (*(lptr+1)=='!') ? RAWMODE | ISPACKED : RAWMODE; - else - segmentflags=0; - if ((segmentflags & ISPACKED)!=0) - lptr+=1; /* skip '!' character */ - if ((segmentflags & RAWMODE)!=0) - lptr+=1; /* skip "escape" character too */ - assert(*lptr=='\"'); - lptr+=1; - if (stringflags==-1) - stringflags=segmentflags; - else if (stringflags!=segmentflags) - error(238); /* mixing packed/unpacked/raw strings in concatenation */ - cat=strchr(tok->str,'\0'); - assert(cat!=NULL); - while (*lptr!='\"' && *lptr!='\0' && (cat-tok->str)len = (size_t)(cat - tok->str); - if (*lptr=='\"') - lptr+=1; /* skip final quote */ - else - error(37); /* invalid (non-terminated) string */ - /* see whether an ellipsis is following the string */ - if (!scanellipsis(lptr)) - break; /* no concatenation of string literals */ - /* there is an ellipses, go on parsing (this time with full preprocessing) */ - while (*lptr<=' ') { - if (*lptr=='\0') { - preprocess_in_lex(); - assert(freading && lptr!=term_expr); - } else { - lptr++; - } /* if */ - } /* while */ - assert(freading && lptr[0]=='.' && lptr[1]=='.' && lptr[2]=='.'); - lptr+=3; - while (*lptr<=' ') { - if (*lptr=='\0') { - preprocess_in_lex(); - assert(freading && lptr!=term_expr); - } else { - lptr++; - } /* if */ - } /* while */ - if (!freading || !(*lptr=='\"' -#if 0 - || *lptr==sc_ctrlchar && *(lptr+1)=='\"' - || *lptr=='!' && *(lptr+1)=='\"' - || *lptr=='!' && *(lptr+1)==sc_ctrlchar && *(lptr+2)=='\"' - || *lptr==sc_ctrlchar && *(lptr+1)=='!' && *(lptr+2)=='\"' -#endif - )) - { - error(37); /* invalid string concatenation */ - break; - } /* if */ - } /* for */ - if (sc_packstr) - stringflags ^= ISPACKED; /* invert packed/unpacked parameters */ - if ((stringflags & ISPACKED)!=0) - packedstring((unsigned char *)tok->str,stringflags); - else - unpackedstring((unsigned char *)tok->str,stringflags); - } else if (*lptr=='\'') { /* character literal */ - lptr+=1; /* skip quote */ - tok->id = tNUMBER; - *lexvalue = tok->value = litchar(&lptr,UTF8MODE); - if (*lptr=='\'') - lptr+=1; /* skip final quote */ - else - error(27); /* invalid character constant (must be one character) */ - } else if (*lptr==';') { /* semicolumn resets "error" flag */ - tok->id = ';'; - lptr+=1; - errorset(sRESET,0); /* reset error flag (clear the "panic mode")*/ - } else { - tok->id = *lptr; /* if every match fails, return the character */ - lptr+=1; /* increase the "lptr" pointer */ - } /* if */ - - if (pc_docexpr) { /* optionally concatenate to documentation string */ - char *docstr=(char*)malloc(((int)(lptr-starttoken)+1)*sizeof(char)); - if (docstr!=NULL) { - strlcpy(docstr,(char*)starttoken,(int)(lptr-starttoken)+1); - insert_autolist(docstr); - free(docstr); - } /* if */ - } /* if */ - tok->end.line = fline; - tok->end.col = (int)(lptr - pline); - return tok->id; -} - -/* lexpush - * - * Pushes a token back, so the next call to lex() will return the token - * last examined, instead of a new token. - * - * Only one token can be pushed back. - * - * In fact, lex() already stores the information it finds into global - * variables, so all that is to be done is set a flag that informs lex() - * to read and return the information from these variables, rather than - * to read in a new token from the input file. - */ -void lexpush(void) -{ - if (current_token()->id == tPENDING_STRING) { - // Don't push back fake tokens. - return; - } - - assert(sTokenBuffer->depth < MAX_TOKEN_DEPTH); - sTokenBuffer->depth++; - if (sTokenBuffer->cursor == 0) - sTokenBuffer->cursor = MAX_TOKEN_DEPTH - 1; - else - sTokenBuffer->cursor--; - assert(sTokenBuffer->depth <= sTokenBuffer->num_tokens); -} - -/* lexclr - * - * Sets the variable "_pushed" to 0 to make sure lex() will read in a new - * symbol (a not continue with some old one). This is required upon return - * from Assembler mode, and in a few cases after detecting an syntax error. - */ -void lexclr(int clreol) -{ - sTokenBuffer->depth = 0; - if (clreol) { - lptr=(unsigned char*)strchr((char*)pline,'\0'); - assert(lptr!=NULL); - } /* if */ -} - -// Return true if the symbol is ahead, false otherwise. -int lexpeek(int id) -{ - if (matchtoken(id)) { - lexpush(); - return TRUE; - } - return FALSE; -} - -/* matchtoken - * - * This routine is useful if only a simple check is needed. If the token - * differs from the one expected, it is pushed back. - * This function returns 1 for "token found" and 2 for "implied statement - * termination token" found --the statement termination is an end of line in - * an expression where there is no pending operation. Such an implied token - * (i.e. not present in the source code) should not be pushed back, which is - * why it is sometimes important to distinguish the two. - */ -int matchtoken(int token) -{ - cell val; - char *str; - int tok; - - tok = lex(&val, &str); - - if (token == tok) - return 1; - if (token==tTERM && (tok==';' || tok==tENDEXPR)) - return 1; - - if (!sc_needsemicolon && token==tTERM && (_lexnewline || !freading)) { - /* Push "tok" back, because it is the token following the implicit statement - * termination (newline) token. - */ - lexpush(); - return 2; - } - - lexpush(); - return 0; -} - -/* tokeninfo - * - * Returns additional information of a token after using "matchtoken()" - * or needtoken(). It does no harm using this routine after a call to - * "lex()", but lex() already returns the same information. - * - * The token itself is the return value. Normally, this one is already known. - */ -int tokeninfo(cell *val,char **str) -{ - *val = current_token()->value; - *str = current_token()->str; - return current_token()->id; -} - -/* needtoken - * - * This routine checks for a required token and gives an error message if - * it isn't there (and returns 0/FALSE in that case). Like function matchtoken(), - * this function returns 1 for "token found" and 2 for "statement termination - * token" found; see function matchtoken() for details. - */ -int needtoken(int token) -{ - char s1[20],s2[20]; - int t; - - if ((t=matchtoken(token))!=0) { - return t; - } else { - /* token already pushed back */ - assert(sTokenBuffer->depth > 0); - if (token<256) - sprintf(s1,"%c",(char)token); /* single character token */ - else - strcpy(s1,sc_tokens[token-tFIRST]); /* multi-character symbol */ - if (!freading) - strcpy(s2,"-end of file-"); - else if (next_token()->id < 256) - sprintf(s2,"%c",(char)next_token()->id); - else - strcpy(s2, sc_tokens[next_token()->id - tFIRST]); - error(1,s1,s2); /* expected ..., but found ... */ - return FALSE; - } /* if */ -} - -// If the next token is on the current line, return that token. Otherwise, -// return tNEWLINE. -int peek_same_line() -{ - // We should not call this without having parsed at least one token. - assert(sTokenBuffer->num_tokens > 0); - - // If there's tokens pushed back, then |fline| is the line of the furthest - // token parsed. If fline == current token's line, we are guaranteed any - // buffered token is still on the same line. - if (sTokenBuffer->depth > 0 && current_token()->end.line == fline) - return next_token()->id; - - // Make sure the next token is lexed by lexing, and then buffering it. - full_token_t *next; - { - token_t tmp; - lextok(&tmp); - next = current_token(); - lexpush(); - } - - // If the next token starts on the line the last token ends, then the next - // token is considered on the same line. - if (next->start.line == current_token()->end.line) - return next->id; - - return tEOL; -} - -int require_newline(int allow_semi) -{ - if (allow_semi) { - // Semicolon must be on the same line. - if (peek_same_line() == ';') - lexpop(); - } - - int tokid = peek_same_line(); - if (tokid == tEOL || tokid == 0) - return TRUE; - - char s[20]; - if (tokid < 256) - sprintf(s, "%c", (char)tokid); - else - strcpy(s, sc_tokens[tokid - tFIRST]); - error(155, s); - return FALSE; -} - -/* match - * - * Compares a series of characters from the input file with the characters - * in "st" (that contains a token). If the token on the input file matches - * "st", the input file pointer "lptr" is adjusted to point to the next - * token, otherwise "lptr" remains unaltered. - * - * If the parameter "end: is true, match() requires that the first character - * behind the recognized token is non-alphanumeric. - * - * Global references: lptr (altered) - */ -static int match(const char *st,int end) -{ - int k; - const unsigned char *ptr; - - k=0; - ptr=lptr; - while (st[k]) { - if ((unsigned char)st[k]!=*ptr) - return 0; - k+=1; - ptr+=1; - } /* while */ - if (end) { /* symbol must terminate with non-alphanumeric char */ - if (alphanum(*ptr)) - return 0; - } /* if */ - lptr=ptr; /* match found, skip symbol */ - return 1; -} - -static void chk_grow_litq(void) -{ - if (litidx>=litmax) { - cell *p; - - litmax+=sDEF_LITMAX; - p=(cell *)realloc(litq,litmax*sizeof(cell)); - if (p==NULL) - error(FATAL_ERROR_ALLOC_OVERFLOW,"literal table"); - litq=p; - } /* if */ -} - -/* litadd - * - * Adds a value at the end of the literal queue. The literal queue is used - * for literal strings used in functions and for initializing array variables. - * - * Global references: litidx (altered) - * litq (altered) - */ -void litadd(cell value) -{ - assert(!sLiteralQueueDisabled); - chk_grow_litq(); - assert(litidx=0 && pos<=litidx); - memmove(litq+(pos+1),litq+pos,(litidx-pos)*sizeof(cell)); - litidx++; - litq[pos]=value; -} - -/* litchar - * - * Return current literal character and increase the pointer to point - * just behind this literal character. - * - * Note: standard "escape sequences" are suported, but the backslash may be - * replaced by another character; the syntax '\ddd' is supported, - * but ddd must be decimal! - */ -static cell litchar(const unsigned char **lptr,int flags) -{ - cell c=0; - const unsigned char *cptr; - - cptr=*lptr; - if ((flags & RAWMODE)!=0 || *cptr!=sc_ctrlchar) { /* no escape character */ - #if !defined NO_UTF8 - if (sc_is_utf8 && (flags & UTF8MODE)!=0) { - c=get_utf8_char(cptr,&cptr); - assert(c>=0); /* file was already scanned for conformance to UTF-8 */ - } else { - #endif - #if !defined NO_CODEPAGE - c=cp_translate(cptr,&cptr); - #else - c=*cptr; - cptr+=1; - #endif - #if !defined NO_UTF8 - } /* if */ - #endif - } else { - cptr+=1; - if (*cptr==sc_ctrlchar) { - c=*cptr; /* \\ == \ (the escape character itself) */ - cptr+=1; - } else { - switch (*cptr) { - case 'a': /* \a == audible alarm */ - c=7; - cptr+=1; - break; - case 'b': /* \b == backspace */ - c=8; - cptr+=1; - break; - case 'e': /* \e == escape */ - c=27; - cptr+=1; - break; - case 'f': /* \f == form feed */ - c=12; - cptr+=1; - break; - case 'n': /* \n == NewLine character */ - c=10; - cptr+=1; - break; - case 'r': /* \r == carriage return */ - c=13; - cptr+=1; - break; - case 't': /* \t == horizontal TAB */ - c=9; - cptr+=1; - break; - case 'v': /* \v == vertical TAB */ - c=11; - cptr+=1; - break; - case 'x': - { - int digits = 0; - cptr+=1; - c=0; - while (ishex(*cptr) && digits < 2) { - if (isdigit(*cptr)) - c=(c<<4)+(*cptr-'0'); - else - c=(c<<4)+(tolower(*cptr)-'a'+10); - cptr++; - digits++; - } /* while */ - if (*cptr==';') - cptr++; /* swallow a trailing ';' */ - break; - } - case '\'': /* \' == ' (single quote) */ - case '"': /* \" == " (single quote) */ - case '%': /* \% == % (percent) */ - c=*cptr; - cptr+=1; - break; - default: - if (isdigit(*cptr)) { /* \ddd */ - c=0; - while (*cptr>='0' && *cptr<='9') /* decimal! */ - c=c*10 + *cptr++ - '0'; - if (*cptr==';') - cptr++; /* swallow a trailing ';' */ - } else { - error(27); /* invalid character constant */ - } /* if */ - } /* switch */ - } /* if */ - } /* if */ - *lptr=cptr; - assert(c>=0); - return c; -} - -/* alpha - * - * Test if character "c" is alphabetic ("a".."z"), an underscore ("_") - * or an "at" sign ("@"). The "@" is an extension to standard C. - */ -static int alpha(char c) -{ - return (isalpha(c) || c=='_' || c==PUBLIC_CHAR); -} - -/* alphanum - * - * Test if character "c" is alphanumeric ("a".."z", "0".."9", "_" or "@") - */ -int alphanum(char c) -{ - return (alpha(c) || isdigit(c)); -} - -/* ishex - * - * Test if character "c" is a hexadecimal digit ("0".."9" or "a".."f"). - */ -int ishex(char c) -{ - return (c>='0' && c<='9') || (c>='a' && c<='f') || (c>='A' && c<='F'); -} - -/* The local variable table must be searched backwards, so that the deepest - * nesting of local variables is searched first. The simplest way to do - * this is to insert all new items at the head of the list. - * In the global list, the symbols are kept in sorted order, so that the - * public functions are written in sorted order. - */ -static symbol *add_symbol(symbol *root,symbol *entry,int sort) -{ - symbol *newsym; - int global = root==&glbtab; - - if (sort) - while (root->next!=NULL && strcmp(entry->name,root->next->name)>0) - root=root->next; - - if ((newsym=(symbol *)malloc(sizeof(symbol)))==NULL) { - error(FATAL_ERROR_OOM); - return NULL; - } /* if */ - memcpy(newsym,entry,sizeof(symbol)); - newsym->next=root->next; - root->next=newsym; - if (global) - AddToHashTable(sp_Globals, newsym); - return newsym; -} - -static void free_symbol(symbol *sym) -{ - arginfo *arg; - - /* free all sub-symbol allocated memory blocks, depending on the - * kind of the symbol - */ - assert(sym!=NULL); - if (sym->ident==iFUNCTN) { - /* run through the argument list; "default array" arguments - * must be freed explicitly; the tag list must also be freed */ - assert(sym->dim.arglist!=NULL); - for (arg=sym->dim.arglist; arg->ident!=0; arg++) { - if (arg->ident==iREFARRAY && arg->hasdefault) - free(arg->defvalue.array.data); - assert(arg->tags!=NULL); - free(arg->tags); - } /* for */ - free(sym->dim.arglist); - if (sym->states!=NULL) { - delete_consttable(sym->states); - free(sym->states); - } /* if */ - } else if (sym->ident==iVARIABLE || sym->ident==iARRAY) { - if (sym->states!=NULL) { - delete_consttable(sym->states); - free(sym->states); - } /* if */ - } else if (sym->ident==iCONSTEXPR && (sym->usage & uENUMROOT)==uENUMROOT) { - /* free the constant list of an enum root */ - assert(sym->dim.enumlist!=NULL); - delete_consttable(sym->dim.enumlist); - free(sym->dim.enumlist); - } /* if */ - assert(sym->refer!=NULL); - free(sym->refer); - if (sym->documentation!=NULL) - free(sym->documentation); - free(sym); -} - -void delete_symbol(symbol *root,symbol *sym) -{ - symbol *origRoot=root; - /* find the symbol and its predecessor - * (this function assumes that you will never delete a symbol that is not - * in the table pointed at by "root") - */ - assert(root!=sym); - while (root->next!=sym) { - root=root->next; - assert(root!=NULL); - } /* while */ - - if (origRoot==&glbtab) - RemoveFromHashTable(sp_Globals, sym); - - /* unlink it, then free it */ - root->next=sym->next; - free_symbol(sym); -} - -int get_actual_compound(symbol *sym) -{ - if (sym->ident == iARRAY || sym->ident == iREFARRAY) { - while (sym->parent) - sym = sym->parent; - } - - return sym->compound; -} - -void delete_symbols(symbol *root,int level,int delete_labels,int delete_functions) -{ - symbol *origRoot=root; - symbol *sym,*parent_sym; - constvalue *stateptr; - int mustdelete; - - /* erase only the symbols with a deeper nesting level than the - * specified nesting level */ - while (root->next!=NULL) { - sym=root->next; - if (get_actual_compound(sym)ident) { - case iLABEL: - mustdelete=delete_labels; - break; - case iVARIABLE: - case iARRAY: - /* do not delete global variables if functions are preserved */ - mustdelete=delete_functions; - break; - case iREFERENCE: - /* always delete references (only exist as function parameters) */ - mustdelete=TRUE; - break; - case iREFARRAY: - /* a global iREFARRAY symbol is the return value of a function: delete - * this only if "globals" must be deleted; other iREFARRAY instances - * (locals) are also deleted - */ - mustdelete=delete_functions; - for (parent_sym=sym->parent; parent_sym!=NULL && parent_sym->ident!=iFUNCTN; parent_sym=parent_sym->parent) - assert(parent_sym->ident==iREFARRAY); - assert(parent_sym==NULL || (parent_sym->ident==iFUNCTN && parent_sym->parent==NULL)); - if (parent_sym==NULL || parent_sym->ident!=iFUNCTN) - mustdelete=TRUE; - break; - case iCONSTEXPR: - /* delete constants, except predefined constants */ - mustdelete=delete_functions || (sym->usage & uPREDEF)==0; - break; - case iFUNCTN: - /* optionally preserve globals (variables & functions), but - * NOT native functions - */ - mustdelete=delete_functions || (sym->usage & uNATIVE)!=0; - assert(sym->parent==NULL); - break; - case iMETHODMAP: - // We delete methodmap symbols at the end, but since methodmaps - // themselves get wiped, we null the pointer. - sym->methodmap = nullptr; - mustdelete = delete_functions; - assert(!sym->parent); - break; - case iARRAYCELL: - case iARRAYCHAR: - case iEXPRESSION: - case iVARARGS: - case iACCESSOR: - default: - assert(0); - break; - } /* switch */ - if (mustdelete) { - if (origRoot == &glbtab) - RemoveFromHashTable(sp_Globals, sym); - root->next=sym->next; - free_symbol(sym); - } else { - /* if the function was prototyped, but not implemented in this source, - * mark it as such, so that its use can be flagged - */ - if (sym->ident==iFUNCTN && (sym->usage & uDEFINE)==0) - sym->usage |= uMISSING; - if (sym->ident==iFUNCTN || sym->ident==iVARIABLE || sym->ident==iARRAY) - sym->usage &= ~uDEFINE; /* clear "defined" flag */ - /* set all states as "undefined" too */ - if (sym->states!=NULL) - for (stateptr=sym->states->next; stateptr!=NULL; stateptr=stateptr->next) - stateptr->value=0; - /* for user defined operators, also remove the "prototyped" flag, as - * user-defined operators *must* be declared before use - */ - if (sym->ident==iFUNCTN && !alpha(*sym->name)) - sym->usage &= ~uPROTOTYPED; - root=sym; /* skip the symbol */ - } /* if */ - } /* if */ -} - -static symbol *find_symbol(const symbol *root,const char *name,int fnumber,int automaton,int *cmptag) -{ - symbol *firstmatch=NULL; - symbol *sym=root->next; - int count=0; - unsigned long hash=NameHash(name); - while (sym!=NULL) { - if (hash==sym->hash && strcmp(name,sym->name)==0 /* check name */ - && (sym->parent==NULL || sym->ident==iCONSTEXPR) /* sub-types (hierarchical types) are skipped, except for enum fields */ - && (sym->fnumber<0 || sym->fnumber==fnumber)) /* check file number for scope */ - { - assert(sym->states==NULL || sym->states->next!=NULL); /* first element of the state list is the "root" */ - if (sym->ident==iFUNCTN - || (automaton<0 && sym->states==NULL) - || (automaton>=0 && sym->states!=NULL && state_getfsa(sym->states->next->index)==automaton)) - { - if (cmptag==NULL) - return sym; /* return first match */ - /* return closest match or first match; count number of matches */ - if (firstmatch==NULL) - firstmatch=sym; - assert(cmptag!=NULL); - if (*cmptag==0) - count++; - if (*cmptag==sym->tag) { - *cmptag=1; /* good match found, set number of matches to 1 */ - return sym; - } /* if */ - } /* if */ - } /* */ - sym=sym->next; - } /* while */ - if (cmptag!=NULL && firstmatch!=NULL) - *cmptag=count; - return firstmatch; -} - -static symbol *find_symbol_child(const symbol *root,const symbol *sym) -{ - symbol *ptr=root->next; - while (ptr!=NULL) { - if (ptr->parent==sym) - return ptr; - ptr=ptr->next; - } /* while */ - return NULL; -} - -/* Adds "bywhom" to the list of referrers of "entry". Typically, - * bywhom will be the function that uses a variable or that calls - * the function. - */ -int refer_symbol(symbol *entry,symbol *bywhom) -{ - int count; - - assert(bywhom!=NULL); /* it makes no sense to add a "void" referrer */ - assert(entry!=NULL); - assert(entry->refer!=NULL); - - /* see if it is already there */ - for (count=0; countnumrefers && entry->refer[count]!=bywhom; count++) - /* nothing */; - if (countnumrefers) { - assert(entry->refer[count]==bywhom); - return TRUE; - } /* if */ - - /* see if there is an empty spot in the referrer list */ - for (count=0; countnumrefers && entry->refer[count]!=NULL; count++) - /* nothing */; - assert(count <= entry->numrefers); - if (count==entry->numrefers) { - symbol **refer; - int newsize=2*entry->numrefers; - assert(newsize>0); - /* grow the referrer list */ - refer=(symbol**)realloc(entry->refer,newsize*sizeof(symbol*)); - if (refer==NULL) - return FALSE; /* insufficient memory */ - /* initialize the new entries */ - entry->refer=refer; - for (count=entry->numrefers; countrefer[count]=NULL; - count=entry->numrefers; /* first empty spot */ - entry->numrefers=newsize; - } /* if */ - - /* add the referrer */ - assert(entry->refer[count]==NULL); - entry->refer[count]=bywhom; - return TRUE; -} - -void markusage(symbol *sym,int usage) -{ - assert(sym!=NULL); - sym->usage |= (char)usage; - if ((usage & uWRITTEN)!=0) - sym->lnumber=fline; - /* check if (global) reference must be added to the symbol */ - if ((usage & (uREAD | uWRITTEN))!=0) { - /* only do this for global symbols */ - if (sym->vclass==sGLOBAL) { - /* "curfunc" should always be valid, since statements may not occurs - * outside functions; in the case of syntax errors, however, the - * compiler may arrive through this function - */ - if (curfunc!=NULL) - refer_symbol(sym,curfunc); - } /* if */ - } /* if */ -} - -/* findglb - * - * Returns a pointer to the global symbol (if found) or NULL (if not found) - */ -symbol *findglb(const char *name, int filter) -{ - /* find a symbol with a matching automaton first */ - symbol *sym=NULL; - - if (filter>sGLOBAL && sc_curstates>0) { - /* find a symbol whose state list matches the current fsa */ - sym=find_symbol(&glbtab,name,fcurrent,state_getfsa(sc_curstates),NULL); - if (sym!=NULL && sym->ident!=iFUNCTN) { - /* if sym!=NULL, we found a variable in the automaton; now we should - * also verify whether there is an intersection between the symbol's - * state list and the current state list - */ - assert(sym->states!=NULL && sym->states->next!=NULL); - if (!state_conflict_id(sc_curstates,sym->states->next->index)) - sym=NULL; - } /* if */ - } /* if */ - - /* if no symbol with a matching automaton exists, find a variable/function - * that has no state(s) attached to it - */ - if (sym==NULL) - sym=FindInHashTable(sp_Globals,name,fcurrent); - - return sym; -} - -/* findloc - * - * Returns a pointer to the local symbol (if found) or NULL (if not found). - * See add_symbol() how the deepest nesting level is searched first. - */ -symbol *findloc(const char *name) -{ - return find_symbol(&loctab,name,-1,-1,NULL); -} - -symbol *findconst(const char *name,int *cmptag) -{ - symbol *sym; - - sym=find_symbol(&loctab,name,-1,-1,cmptag); /* try local symbols first */ - if (sym==NULL || sym->ident!=iCONSTEXPR) { /* not found, or not a constant */ - if (cmptag) - sym=FindTaggedInHashTable(sp_Globals,name,fcurrent,cmptag); - else - sym=FindInHashTable(sp_Globals,name,fcurrent); - } - if (sym==NULL || sym->ident!=iCONSTEXPR) - return NULL; - assert(sym->parent==NULL || (sym->usage & uENUMFIELD)!=0); - /* ^^^ constants have no hierarchy, but enumeration fields may have a parent */ - return sym; -} - -symbol *finddepend(const symbol *parent) -{ - symbol *sym; - - sym=find_symbol_child(&loctab,parent); /* try local symbols first */ - if (sym==NULL) /* not found */ - sym=find_symbol_child(&glbtab,parent); - return sym; -} - -/* addsym - * - * Adds a symbol to the symbol table (either global or local variables, - * or global and local constants). - */ -symbol *addsym(const char *name,cell addr,int ident,int vclass,int tag,int usage) -{ - symbol entry, **refer; - - /* labels may only be defined once */ - assert(ident!=iLABEL || findloc(name)==NULL); - - /* create an empty referrer list */ - if ((refer=(symbol**)malloc(sizeof(symbol*)))==NULL) { - error(FATAL_ERROR_OOM); - return NULL; - } /* if */ - *refer=NULL; - - /* first fill in the entry */ - memset(&entry,0,sizeof entry); - strcpy(entry.name,name); - entry.hash=NameHash(name); - entry.addr=addr; - entry.codeaddr=code_idx; - entry.vclass=(char)vclass; - entry.ident=(char)ident; - entry.tag=tag; - entry.usage=(char)usage; - entry.fnumber=-1; /* assume global visibility (ignored for local symbols) */ - entry.lnumber=fline; - entry.numrefers=1; - entry.refer=refer; - entry.funcid=0; - - /* then insert it in the list */ - if (vclass==sGLOBAL) - return add_symbol(&glbtab,&entry,TRUE); - return add_symbol(&loctab,&entry,FALSE); -} - -symbol *addvariable(const char *name,cell addr,int ident,int vclass,int tag, - int dim[],int numdim,int idxtag[]) -{ - return addvariable2(name,addr,ident,vclass,tag,dim,numdim,idxtag,0); -} - -symbol *addvariable3(declinfo_t *decl,cell addr,int vclass,int slength) -{ - typeinfo_t *type = &decl->type; - return addvariable2( - decl->name, - addr, - type->ident, - vclass, - type->tag, - type->dim, - type->numdim, - type->idxtag, - slength - ); -} - -symbol *addvariable2(const char *name,cell addr,int ident,int vclass,int tag, - int dim[],int numdim,int idxtag[],int slength) -{ - symbol *sym; - - /* global variables may only be defined once - * One complication is that functions returning arrays declare an array - * with the same name as the function, so the assertion must allow for - * this special case. Another complication is that variables may be - * "redeclared" if they are local to an automaton (and findglb() will find - * the symbol without states if no symbol with states exists). - */ - assert(vclass!=sGLOBAL || (sym=findglb(name,sGLOBAL))==NULL || (sym->usage & uDEFINE)==0 - || (sym->ident==iFUNCTN && sym==curfunc) - || (sym->states==NULL && sc_curstates>0)); - - if (ident==iARRAY || ident==iREFARRAY) { - symbol *parent=NULL,*top; - int level; - sym=NULL; /* to avoid a compiler warning */ - for (level=0; leveldim.array.length=dim[level]; - if (tag == pc_tag_string && level == numdim - 1) { - if (slength == 0) - top->dim.array.length=dim[level] * sizeof(cell); - else - top->dim.array.slength=slength; - } else { - top->dim.array.slength=0; - } - top->dim.array.level=(short)(numdim-level-1); - top->x.tags.index=idxtag[level]; - top->parent=parent; - parent=top; - if (level==0) - sym=top; - } /* for */ - } else { - sym=addsym(name,addr,ident,vclass,tag,uDEFINE); - } /* if */ - return sym; -} - -/* getlabel - * - * Returns te next internal label number. The global variable sc_labnum is - * initialized to zero. - */ -int getlabel(void) -{ - return sc_labnum++; -} - -/* itoh - * - * Converts a number to a hexadecimal string and returns a pointer to that - * string. This function is NOT re-entrant. - */ -char *itoh(ucell val) -{ -static char itohstr[30]; - char *ptr; - int i,nibble[16]; /* a 64-bit hexadecimal cell has 16 nibbles */ - int max; - - #if PAWN_CELL_SIZE==16 - max=4; - #elif PAWN_CELL_SIZE==32 - max=8; - #elif PAWN_CELL_SIZE==64 - max=16; - #else - #error Unsupported cell size - #endif - ptr=itohstr; - for (i=0; i>=4; - } /* endfor */ - i=max-1; - while (nibble[i]==0 && i>0) /* search for highest non-zero nibble */ - i-=1; - while (i>=0){ - if (nibble[i]>=10) - *ptr++=(char)('a'+(nibble[i]-10)); - else - *ptr++=(char)('0'+nibble[i]); - i-=1; - } /* while */ - *ptr='\0'; /* and a zero-terminator */ - return itohstr; -} - -int lextok(token_t *tok) -{ - tok->id = lex(&tok->val, &tok->str); - return tok->id; -} - -int expecttoken(int id, token_t *tok) -{ - int rval = needtoken(id); - if (rval) { - tok->val = current_token()->value; - tok->id = current_token()->id; - tok->str = current_token()->str; - return rval; - } - return FALSE; -} - -int matchtoken2(int id, token_t *tok) -{ - if (matchtoken(id)) { - tok->id = tokeninfo(&tok->val, &tok->str); - return TRUE; - } - return FALSE; -} - -int matchsymbol(token_ident_t *ident) -{ - if (lextok(&ident->tok) != tSYMBOL) { - lexpush(); - return FALSE; - } - strcpy(ident->name, ident->tok.str); - ident->tok.str = ident->name; - return TRUE; -} - -int needsymbol(token_ident_t *ident) -{ - if (!expecttoken(tSYMBOL, &ident->tok)) - return FALSE; - strcpy(ident->name, ident->tok.str); - ident->tok.str = ident->name; - return TRUE; -} diff --git a/sourcepawn/compiler/sc3.cpp b/sourcepawn/compiler/sc3.cpp deleted file mode 100644 index 857ccb78..00000000 --- a/sourcepawn/compiler/sc3.cpp +++ /dev/null @@ -1,3219 +0,0 @@ -/* vim: set ts=8 sts=2 sw=2 tw=99 et: */ -/* Pawn compiler - Recursive descend expresion parser - * - * Copyright (c) ITB CompuPhase, 1997-2005 - * - * This software is provided "as-is", without any express or implied warranty. - * In no event will the authors be held liable for any damages arising from - * the use of this software. - * - * Permission is granted to anyone to use this software for any purpose, - * including commercial applications, and to alter it and redistribute it - * freely, subject to the following restrictions: - * - * 1. The origin of this software must not be misrepresented; you must not - * claim that you wrote the original software. If you use this software in - * a product, an acknowledgment in the product documentation would be - * appreciated but is not reeq;quired. - * 2. Altered source versions must be plainly marked as such, and must not be - * misrepresented as being the original software. - * 3. This notice may not be removed or altered from any source distribution. - * - * Version: $Id$ - */ -#include -#include -#include /* for _MAX_PATH */ -#include -#if defined FORTIFY - #include -#endif -#include "sc.h" -#include "sctracker.h" - -static int skim(int *opstr,void (*testfunc)(int),int dropval,int endval, - int (*hier)(value*),value *lval); -static void dropout(int lvalue,void (*testfunc)(int val),int exit1,value *lval); -static int plnge(int *opstr,int opoff,int (*hier)(value *lval),value *lval, - const char *forcetag,int chkbitwise); -static int plnge1(int (*hier)(value *lval),value *lval); -static void plnge2(void (*oper)(void), - int (*hier)(value *lval), - value *lval1,value *lval2); -static cell calc(cell left,void (*oper)(),cell right,char *boolresult); -static int hier14(value *lval); -static int hier13(value *lval); -static int hier12(value *lval); -static int hier11(value *lval); -static int hier10(value *lval); -static int hier9(value *lval); -static int hier8(value *lval); -static int hier7(value *lval); -static int hier6(value *lval); -static int hier5(value *lval); -static int hier4(value *lval); -static int hier3(value *lval); -static int hier2(value *lval); -static int hier1(value *lval1); -static int primary(value *lval); -static void clear_value(value *lval); -static void callfunction(symbol *sym, const svalue *implicitthis, value *lval_result, int matchparanthesis); -static int dbltest(void (*oper)(),value *lval1,value *lval2); -static int commutative(void (*oper)()); -static int constant(value *lval); - -static char lastsymbol[sNAMEMAX+1]; /* name of last function/variable */ -static int bitwise_opercount; /* count of bitwise operators in an expression */ - -/* Function addresses of binary operators for signed operations */ -static void (*op1[17])(void) = { - os_mult,os_div,os_mod, /* hier3, index 0 */ - ob_add,ob_sub, /* hier4, index 3 */ - ob_sal,os_sar,ou_sar, /* hier5, index 5 */ - ob_and, /* hier6, index 8 */ - ob_xor, /* hier7, index 9 */ - ob_or, /* hier8, index 10 */ - os_le,os_ge,os_lt,os_gt, /* hier9, index 11 */ - ob_eq,ob_ne, /* hier10, index 15 */ -}; -/* These two functions are defined because the functions inc() and dec() in - * SC4.C have a different prototype than the other code generation functions. - * The arrays for user-defined functions use the function pointers for - * identifying what kind of operation is requested; these functions must all - * have the same prototype. As inc() and dec() are special cases already, it - * is simplest to add two "do-nothing" functions. - */ -static void user_inc(void) {} -static void user_dec(void) {} - -/* - * Searches for a binary operator a list of operators. The list is stored in - * the array "list". The last entry in the list should be set to 0. - * - * The index of an operator in "list" (if found) is returned in "opidx". If - * no operator is found, nextop() returns 0. - * - * If an operator is found in the expression, it cannot be used in a function - * call with omitted parantheses. Mark this... - * - * Global references: sc_allowproccall (modified) - */ -static int nextop(int *opidx,int *list) -{ - *opidx=0; - while (*list){ - if (matchtoken(*list)){ - sc_allowproccall=FALSE; - return TRUE; /* found! */ - } else { - list+=1; - *opidx+=1; - } /* if */ - } /* while */ - return FALSE; /* entire list scanned, nothing found */ -} - -int check_userop(void (*oper)(void),int tag1,int tag2,int numparam, - value *lval,int *resulttag) -{ - static const char *binoperstr[] = { - "*", "/", "%", "+", "-", "", "", "", - "", "", "", "<=", ">=", "<", ">", "==", "!=" - }; - static int binoper_savepri[] = { FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, - FALSE, FALSE, FALSE, FALSE, FALSE, - TRUE, TRUE, TRUE, TRUE, FALSE, FALSE - }; - static const char *unoperstr[] = { "!", "-", "++", "--" }; - static void (*unopers[])(void) = { lneg, neg, user_inc, user_dec }; - - char opername[4] = "", symbolname[sNAMEMAX+1]; - size_t i; - int swapparams,savepri,savealt; - int paramspassed; - symbol *sym; - - /* since user-defined operators on untagged operands are forbidden, we have - * a quick exit. - */ - assert(numparam==1 || numparam==2); - if (tag1==0 && (numparam==1 || tag2==0)) - return FALSE; - - savepri=savealt=FALSE; - /* find the name with the operator */ - if (numparam==2) { - if (oper==NULL) { - /* assignment operator: a special case */ - strcpy(opername,"="); - if (lval!=NULL && (lval->ident==iARRAYCELL || lval->ident==iARRAYCHAR)) - savealt=TRUE; - } else { - assert( (sizeof binoperstr / sizeof binoperstr[0]) == (sizeof op1 / sizeof op1[0]) ); - for (i=0; iusage & uDEFINE)==0*/) { /* ??? should not check uDEFINE; first pass clears these bits */ - /* check for commutative operators */ - if (tag1==tag2 || oper==NULL || !commutative(oper)) - return FALSE; /* not commutative, cannot swap operands */ - /* if arrived here, the operator is commutative and the tags are different, - * swap tags and try again - */ - assert(numparam==2); /* commutative operator must be a binary operator */ - operator_symname(symbolname,opername,tag2,tag1,numparam,tag1); - swapparams=TRUE; - sym=findglb(symbolname,sGLOBAL); - if (sym==NULL /*|| (sym->usage & uDEFINE)==0*/) - return FALSE; - } /* if */ - - /* check existance and the proper declaration of this function */ - if ((sym->usage & uMISSING)!=0 || (sym->usage & uPROTOTYPED)==0) { - char symname[2*sNAMEMAX+16]; /* allow space for user defined operators */ - funcdisplayname(symname,sym->name); - if ((sym->usage & uMISSING)!=0) - error(4,symname); /* function not defined */ - if ((sym->usage & uPROTOTYPED)==0) - error(71,symname); /* operator must be declared before use */ - } /* if */ - - /* we don't want to use the redefined operator in the function that - * redefines the operator itself, otherwise the snippet below gives - * an unexpected recursion: - * fixed:operator+(fixed:a, fixed:b) - * return a + b - */ - if (sym==curfunc) - return FALSE; - - /* for increment and decrement operators, the symbol must first be loaded - * (and stored back afterwards) - */ - if (oper==user_inc || oper==user_dec) { - assert(!savepri); - assert(lval!=NULL); - if (lval->ident==iARRAYCELL || lval->ident==iARRAYCHAR) - pushreg(sPRI); /* save current address in PRI */ - if (lval->ident!=iACCESSOR) - rvalue(lval); /* get the symbol's value in PRI */ - } /* if */ - - assert(!savepri || !savealt); /* either one MAY be set, but not both */ - if (savepri) { - /* the chained comparison operators require that the ALT register is - * unmodified, so we save it here; actually, we save PRI because the normal - * instruction sequence (without user operator) swaps PRI and ALT - */ - pushreg(sPRI); /* right-hand operand is in PRI */ - } else if (savealt) { - /* for the assignment operator, ALT may contain an address at which the - * result must be stored; this address must be preserved accross the - * call - */ - assert(lval!=NULL); /* this was checked earlier */ - assert(lval->ident==iARRAYCELL || lval->ident==iARRAYCHAR); /* checked earlier */ - pushreg(sALT); - } /* if */ - - /* push parameters, call the function */ - paramspassed= (oper==NULL) ? 1 : numparam; - switch (paramspassed) { - case 1: - pushreg(sPRI); - break; - case 2: - /* note that 1) a function expects that the parameters are pushed - * in reversed order, and 2) the left operand is in the secondary register - * and the right operand is in the primary register */ - if (swapparams) { - pushreg(sALT); - pushreg(sPRI); - } else { - pushreg(sPRI); - pushreg(sALT); - } /* if */ - break; - default: - assert(0); - } /* switch */ - markexpr(sPARM,NULL,0); /* mark the end of a sub-expression */ - pushval((cell)paramspassed /* *sizeof(cell)*/ ); - assert(sym->ident==iFUNCTN); - ffcall(sym,NULL,paramspassed); - if (sc_status!=statSKIP) - markusage(sym,uREAD); /* do not mark as "used" when this call itself is skipped */ - if ((sym->usage & uNATIVE)!=0 && sym->x.lib!=NULL) - sym->x.lib->value += 1; /* increment "usage count" of the library */ - sideeffect=TRUE; /* assume functions carry out a side-effect */ - assert(resulttag!=NULL); - *resulttag=sym->tag; /* save tag of the called function */ - - if (savepri || savealt) - popreg(sALT); /* restore the saved PRI/ALT that into ALT */ - if (oper==user_inc || oper==user_dec) { - assert(lval!=NULL); - if (lval->ident==iARRAYCELL || lval->ident==iARRAYCHAR) - popreg(sALT); /* restore address (in ALT) */ - if (lval->ident!=iACCESSOR) { - store(lval); /* store PRI in the symbol */ - moveto1(); /* make sure PRI is restored on exit */ - } - } /* if */ - return TRUE; -} - -int checktags_string(int tags[], int numtags, value *sym1) -{ - int i; - if (sym1->ident == iARRAY || sym1->ident == iREFARRAY) - { - return FALSE; - } - for (i=0; itag == pc_tag_string && tags[i] == 0) || - (sym1->tag == 0 && tags[i] == pc_tag_string)) - return TRUE; - } - return FALSE; -} - -int checktag_string(value *sym1, value *sym2) -{ - if (sym1->ident == iARRAY || sym2->ident == iARRAY || - sym1->ident == iREFARRAY || sym2->ident == iREFARRAY) - { - return FALSE; - } - if ((sym1->tag == pc_tag_string && sym2->tag == 0) || - (sym1->tag == 0 && sym2->tag == pc_tag_string)) - { - return TRUE; - } - - return FALSE; -} - -const char *type_to_name(int tag) -{ - if (tag == 0) - return "int"; - if (tag == sc_rationaltag) - return "float"; - if (tag == pc_tag_string) - return "char"; - if (tag == pc_anytag) - return "any"; - - const char *name = pc_tagname(tag); - if (name) - return name; - - if (tag & FUNCTAG) - return "function"; - return "unknown"; -} - -int matchtag_string(int ident, int tag) -{ - if (ident == iARRAY || ident == iREFARRAY) - return FALSE; - return (tag == pc_tag_string) ? TRUE : FALSE; -} - -static int obj_typeerror(int id, int tag1, int tag2) -{ - const char *left = pc_tagname(tag1); - const char *right = pc_tagname(tag2); - if (!left || strcmp(left, "_") == 0) - left = "int"; - if (!right || strcmp(right, "_") == 0) - right = "int"; - error(id, right, left); - return FALSE; -} - -static int matchobjecttags(int formaltag, int actualtag, int flags) -{ - if ((flags & MATCHTAG_COMMUTATIVE) && - (formaltag == pc_tag_null_t || formaltag == pc_tag_nullfunc_t)) - { - // Bypass the check immediately after for non-object coercion. - int tmp = actualtag; - actualtag = formaltag; - formaltag = tmp; - } - - // objects never coerce to non-objects, YET. - if ((formaltag & OBJECTTAG) && !(actualtag & OBJECTTAG)) - return obj_typeerror(132, formaltag, actualtag); - - if (actualtag == pc_tag_nullfunc_t) { - // All functions are nullable. We use a separate constant for backward - // compatibility; plugins and extensions check -1, not 0. - if (formaltag & FUNCTAG) - return TRUE; - - error(154, pc_tagname(formaltag)); - return FALSE; - } - - if (actualtag == pc_tag_null_t) { - // All objects are nullable. - if (formaltag & OBJECTTAG) - return TRUE; - - // Some methodmaps are nullable. The nullable property is inherited - // automatically. - methodmap_t *map = methodmap_find_by_tag(formaltag); - if (map && map->nullable) - return TRUE; - - error(148, pc_tagname(formaltag)); - return FALSE; - } - - if (!(formaltag & OBJECTTAG) && (actualtag & OBJECTTAG)) - return obj_typeerror(131, formaltag, actualtag); - - // Every object coerces to "object". - if (formaltag == pc_tag_object) - return TRUE; - - if (flags & MATCHTAG_COERCE) - return obj_typeerror(134, formaltag, actualtag); - - methodmap_t *map = methodmap_find_by_tag(actualtag); - for (; map; map = map->parent) { - if (map->tag == formaltag) - return TRUE; - } - - return obj_typeerror(133, formaltag, actualtag); -} - -static int matchreturntag(const functag_t *formal, const functag_t *actual) -{ - if (formal->ret_tag == actual->ret_tag) - return TRUE; - if (formal->ret_tag == pc_tag_void) { - if (actual->ret_tag == 0 && !(actual->usage & uRETVALUE)) - return TRUE; - } - return FALSE; -} - -static int funcarg_compare(const funcarg_t *formal, const funcarg_t *actual) -{ - // Check type. - if (actual->ident != formal->ident) - return FALSE; - - // Check rank. - if (actual->dimcount != formal->dimcount) - return FALSE; - - // Check arity. - for (int i = 0; i < formal->dimcount; i++) { - if (actual->dims[i] != formal->dims[i]) - return FALSE; - } - - // Check tags. - if (actual->tagcount != formal->tagcount) - return FALSE; - for (int i = 0; i < formal->tagcount; i++) { - // Note we invert the order we pass things to matchtag() here. If the - // typedef specifies base type X, and the function specifies derived - // type Y, we want this to type since such an assignment is valid. - // - // Most programming languages do not subtype arguments like this. We do - // it in SourcePawn to preserve compatibility during the Transitional - // Syntax effort. - int actual_tag = actual->tags[i]; - int formal_tag = formal->tags[i]; - if (!matchtag(actual_tag, formal_tag, MATCHTAG_SILENT|MATCHTAG_COERCE)) - return FALSE; - } - - return TRUE; -} - -static int functag_compare(const functag_t *formal, const functag_t *actual) -{ - // Check return types. - if (!matchreturntag(formal, actual)) - return FALSE; - - // Make sure there are no trailing arguments. - if (actual->argcount > formal->argcount) - return FALSE; - - // Check arguments. - for (int i = 0; i < formal->argcount; i++) { - const funcarg_t *formal_arg = &formal->args[i]; - - if (i >= actual->argcount) { - if (formal_arg->ommittable) - return TRUE; - return FALSE; - } - - const funcarg_t *actual_arg = &actual->args[i]; - if (!funcarg_compare(formal_arg, actual_arg)) - return FALSE; - } - - return TRUE; -} - -static int matchfunctags(int formaltag, int actualtag) -{ - if (formaltag == pc_functag && (actualtag & FUNCTAG)) - return TRUE; - - if (actualtag == pc_tag_nullfunc_t) - return TRUE; - - if (!(actualtag & FUNCTAG)) - return FALSE; - - functag_t *actual = functag_find_intrinsic(actualtag); - if (!actual) - return FALSE; - - funcenum_t *e = funcenums_find_by_tag(formaltag); - if (!e) - return FALSE; - - for (functag_t *formal = e->first; formal; formal = formal->next) { - if (functag_compare(formal, actual)) - return TRUE; - } - - return FALSE; -} - -int matchtag(int formaltag, int actualtag, int flags) -{ - if (formaltag == actualtag) - return TRUE; - - if ((formaltag & OBJECTTAG) || (actualtag & OBJECTTAG)) - return matchobjecttags(formaltag, actualtag, flags); - - if ((actualtag & FUNCTAG) && !(formaltag & FUNCTAG)) { - // We're being given a function, but the destination is not a function. - error(130); - return FALSE; - } - - /* if the formal tag is zero and the actual tag is not "fixed", the actual - * tag is "coerced" to zero - */ - if ((flags & MATCHTAG_COERCE) && !formaltag && !(actualtag & FIXEDTAG)) - return TRUE; - - if (formaltag == pc_anytag || actualtag == pc_anytag) - return TRUE; - - if (formaltag & FUNCTAG) { - if (!matchfunctags(formaltag, actualtag)) { - error(100); - return FALSE; - } - return TRUE; - } - - if (flags & (MATCHTAG_COERCE|MATCHTAG_DEDUCE)) { - // See if the tag has a methodmap associated with it. If so, see if the given - // tag is anywhere on the inheritance chain. - methodmap_t *map = methodmap_find_by_tag(actualtag); - if (map) { - for (; map; map = map->parent) { - if (map->tag == formaltag) - return TRUE; - } - } - } - - if (!(flags & MATCHTAG_SILENT)) - error(213); - return FALSE; -} - -/* - * The AMX pseudo-processor has no direct support for logical (boolean) - * operations. These have to be done via comparing and jumping. Since we are - * already jumping through the code, we might as well implement an "early - * drop-out" evaluation (also called "short-circuit"). This conforms to - * standard C: - * - * expr1 || expr2 expr2 will only be evaluated if expr1 is false. - * expr1 && expr2 expr2 will only be evaluated if expr1 is true. - * - * expr1 || expr2 && expr3 expr2 will only be evaluated if expr1 is false - * and expr3 will only be evaluated if expr1 is - * false and expr2 is true. - * - * Code generation for the last example proceeds thus: - * - * evaluate expr1 - * operator || found - * jump to "l1" if result of expr1 not equal to 0 - * evaluate expr2 - * -> operator && found; skip to higher level in hierarchy diagram - * jump to "l2" if result of expr2 equal to 0 - * evaluate expr3 - * jump to "l2" if result of expr3 equal to 0 - * set expression result to 1 (true) - * jump to "l3" - * l2: set expression result to 0 (false) - * l3: - * <- drop back to previous hierarchy level - * jump to "l1" if result of expr2 && expr3 not equal to 0 - * set expression result to 0 (false) - * jump to "l4" - * l1: set expression result to 1 (true) - * l4: - * - */ - -/* Skim over terms adjoining || and && operators - * dropval The value of the expression after "dropping out". An "or" drops - * out when the left hand is TRUE, so dropval must be 1 on "or" - * expressions. - * endval The value of the expression when no expression drops out. In an - * "or" expression, this happens when both the left hand and the - * right hand are FALSE, so endval must be 0 for "or" expressions. - */ -static int skim(int *opstr,void (*testfunc)(int),int dropval,int endval, - int (*hier)(value*),value *lval) -{ - int lvalue,hits,droplab,endlab,opidx; - int allconst,foundop; - cell constval; - int index; - cell cidx; - - stgget(&index,&cidx); /* mark position in code generator */ - hits=FALSE; /* no logical operators "hit" yet */ - allconst=TRUE; /* assume all values "const" */ - constval=0; - droplab=0; /* to avoid a compiler warning */ - for ( ;; ) { - lvalue=plnge1(hier,lval); /* evaluate left expression */ - - allconst= allconst && (lval->ident==iCONSTEXPR); - if (allconst) { - if (hits) { - /* one operator was already found */ - if (testfunc==jmp_ne0) - lval->constval= lval->constval || constval; - else - lval->constval= lval->constval && constval; - } /* if */ - constval=lval->constval; /* save result accumulated so far */ - } /* if */ - - foundop=nextop(&opidx,opstr); - if ((foundop || hits) && (lval->ident==iARRAY || lval->ident==iREFARRAY)) - error(33, lval->sym ? lval->sym->name : "-unknown-"); /* array was not indexed in an expression */ - if (foundop) { - if (!hits) { - /* this is the first operator in the list */ - hits=TRUE; - droplab=getlabel(); - } /* if */ - dropout(lvalue,testfunc,droplab,lval); - } else if (hits) { /* no (more) identical operators */ - dropout(lvalue,testfunc,droplab,lval); /* found at least one operator! */ - ldconst(endval,sPRI); - jumplabel(endlab=getlabel()); - setlabel(droplab); - ldconst(dropval,sPRI); - setlabel(endlab); - lval->sym=NULL; - lval->tag=pc_addtag("bool"); /* force tag to be "bool" */ - if (allconst) { - lval->ident=iCONSTEXPR; - lval->constval=constval; - stgdel(index,cidx); /* scratch generated code and calculate */ - } else { - lval->ident=iEXPRESSION; - lval->constval=0; - } /* if */ - return FALSE; - } else { - return lvalue; /* none of the operators in "opstr" were found */ - } /* if */ - - } /* while */ -} - -/* - * Reads into the primary register the variable pointed to by lval if - * plunging through the hierarchy levels detected an lvalue. Otherwise - * if a constant was detected, it is loaded. If there is no constant and - * no lvalue, the primary register must already contain the expression - * result. - * - * After that, the compare routines "jmp_ne0" or "jmp_eq0" are called, which - * compare the primary register against 0, and jump to the "early drop-out" - * label "exit1" if the condition is true. - */ -static void dropout(int lvalue,void (*testfunc)(int val),int exit1,value *lval) -{ - if (lvalue) - rvalue(lval); - else if (lval->ident==iCONSTEXPR) - ldconst(lval->constval,sPRI); - (*testfunc)(exit1); -} - -static void checkfunction(value *lval) -{ - symbol *sym=lval->sym; - - if (sym==NULL || (sym->ident!=iFUNCTN && sym->ident!=iREFFUNC)) - return; /* no known symbol, or not a function result */ - - if ((sym->usage & uDEFINE)!=0) { - /* function is defined, can now check the return value (but make an - * exception for directly recursive functions) - */ - if (sym!=curfunc && (sym->usage & uRETVALUE)==0) { - char symname[2*sNAMEMAX+16]; /* allow space for user defined operators */ - funcdisplayname(symname,sym->name); - error(209,symname); /* function should return a value */ - } /* if */ - } else { - /* function not yet defined, set */ - sym->usage|=uRETVALUE; /* make sure that a future implementation of - * the function uses "return " */ - } /* if */ -} - -/* - * Plunge to a lower level - */ -static int plnge(int *opstr,int opoff,int (*hier)(value *lval),value *lval, - const char *forcetag,int chkbitwise) -{ - int lvalue,opidx; - int count; - value lval2 = {0}; - - lvalue=plnge1(hier,lval); - if (nextop(&opidx,opstr)==0) - return lvalue; /* no operator in "opstr" found */ - if (lvalue) - rvalue(lval); - count=0; - do { - if (chkbitwise && count++>0 && bitwise_opercount!=0) - error(212); - opidx+=opoff; /* add offset to index returned by nextop() */ - plnge2(op1[opidx],hier,lval,&lval2); - if (op1[opidx]==ob_and || op1[opidx]==ob_or) - bitwise_opercount++; - if (forcetag!=NULL) - lval->tag=pc_addtag(forcetag); - } while (nextop(&opidx,opstr)); /* do */ - return FALSE; /* result of expression is not an lvalue */ -} - -/* plnge_rel - * - * Binary plunge to lower level; this is very simular to plnge, but - * it has special code generation sequences for chained operations. - */ -static int plnge_rel(int *opstr,int opoff,int (*hier)(value *lval),value *lval) -{ - int lvalue,opidx; - value lval2={0}; - int count; - char boolresult; - - /* this function should only be called for relational operators */ - assert(op1[opoff]==os_le); - lvalue=plnge1(hier,lval); - if (nextop(&opidx,opstr)==0) - return lvalue; /* no operator in "opstr" found */ - if (lvalue) - rvalue(lval); - count=0; - lval->boolresult=TRUE; - do { - /* same check as in plnge(), but "chkbitwise" is always TRUE */ - if (count>0 && bitwise_opercount!=0) - error(212); - if (count>0) { - relop_prefix(); - boolresult=lval->boolresult; - *lval=lval2; /* copy right hand expression of the previous iteration */ - lval->boolresult=boolresult; - } /* if */ - opidx+=opoff; - plnge2(op1[opidx],hier,lval,&lval2); - if (count++>0) - relop_suffix(); - } while (nextop(&opidx,opstr)); /* enddo */ - lval->constval=lval->boolresult; - lval->tag=pc_addtag("bool"); /* force tag to be "bool" */ - return FALSE; /* result of expression is not an lvalue */ -} - -/* plnge1 - * - * Unary plunge to lower level - * Called by: skim(), plnge(), plnge2(), plnge_rel(), hier14() and hier13() - */ -static int plnge1(int (*hier)(value *lval),value *lval) -{ - int lvalue,index; - cell cidx; - - stgget(&index,&cidx); /* mark position in code generator */ - lvalue=(*hier)(lval); - if (lval->ident==iCONSTEXPR) - stgdel(index,cidx); /* load constant later */ - return lvalue; -} - -/* plnge2 - * - * Binary plunge to lower level - * Called by: plnge(), plnge_rel(), hier14() and hier1() - */ -static void plnge2(void (*oper)(void), - int (*hier)(value *lval), - value *lval1,value *lval2) -{ - int index; - cell cidx; - - stgget(&index,&cidx); /* mark position in code generator */ - if (lval1->ident==iCONSTEXPR) { /* constant on left side; it is not yet loaded */ - if (plnge1(hier,lval2)) - rvalue(lval2); /* load lvalue now */ - else if (lval2->ident==iCONSTEXPR) - ldconst(lval2->constval<constval<ident==iCONSTEXPR) { /* constant on right side */ - if (commutative(oper)) { /* test for commutative operators */ - value lvaltmp = {0}; - stgdel(index,cidx); /* scratch pushreg() and constant fetch (then - * fetch the constant again */ - ldconst(lval2->constval<constval<ident==iARRAY || lval1->ident==iREFARRAY) { - const char *ptr=(lval1->sym!=NULL) ? lval1->sym->name : "-unknown-"; - error(33,ptr); /* array must be indexed */ - } else if (lval2->ident==iARRAY || lval2->ident==iREFARRAY) { - const char *ptr=(lval2->sym!=NULL) ? lval2->sym->name : "-unknown-"; - error(33,ptr); /* array must be indexed */ - } /* if */ - /* ??? ^^^ should do same kind of error checking with functions */ - - /* check whether an "operator" function is defined for the tag names - * (a constant expression cannot be optimized in that case) - */ - if (check_userop(oper,lval1->tag,lval2->tag,2,NULL,&lval1->tag)) { - lval1->ident=iEXPRESSION; - lval1->constval=0; - } else if (lval1->ident==iCONSTEXPR && lval2->ident==iCONSTEXPR) { - /* only constant expression if both constant */ - stgdel(index,cidx); /* scratch generated code and calculate */ - matchtag(lval1->tag,lval2->tag,FALSE); - lval1->constval=calc(lval1->constval,oper,lval2->constval,&lval1->boolresult); - } else { - // For the purposes of tag matching, we consider the order to be irrelevant. - if (!checktag_string(lval1, lval2)) - matchtag(lval1->tag, lval2->tag, MATCHTAG_COMMUTATIVE|MATCHTAG_DEDUCE); - (*oper)(); /* do the (signed) operation */ - lval1->ident=iEXPRESSION; - } /* if */ - } /* if */ -} - -static cell flooreddiv(cell a,cell b,int return_remainder) -{ - cell q,r; - - if (b==0) { - error(29); - return 0; - } /* if */ - /* first implement truncated division in a portable way */ - #define IABS(a) ((a)>=0 ? (a) : (-a)) - q=IABS(a)/IABS(b); - if ((cell)(a ^ b)<0) - q=-q; /* swap sign if either "a" or "b" is negative (but not both) */ - r=a-q*b; /* calculate the matching remainder */ - /* now "fiddle" with the values to get floored division */ - if (r!=0 && (cell)(r ^ b)<0) { - q--; - r+=b; - } /* if */ - return return_remainder ? r : q; -} - -static cell calc(cell left,void (*oper)(),cell right,char *boolresult) -{ - if (oper==ob_or) - return (left | right); - else if (oper==ob_xor) - return (left ^ right); - else if (oper==ob_and) - return (left & right); - else if (oper==ob_eq) - return (left == right); - else if (oper==ob_ne) - return (left != right); - else if (oper==os_le) - return *boolresult &= (char)(left <= right), right; - else if (oper==os_ge) - return *boolresult &= (char)(left >= right), right; - else if (oper==os_lt) - return *boolresult &= (char)(left < right), right; - else if (oper==os_gt) - return *boolresult &= (char)(left > right), right; - else if (oper==os_sar) - return (left >> (int)right); - else if (oper==ou_sar) - return ((ucell)left >> (ucell)right); - else if (oper==ob_sal) - return ((ucell)left << (int)right); - else if (oper==ob_add) - return (left + right); - else if (oper==ob_sub) - return (left - right); - else if (oper==os_mult) - return (left * right); - else if (oper==os_div) - return flooreddiv(left,right,0); - else if (oper==os_mod) - return flooreddiv(left,right,1); - else - error(29); /* invalid expression, assumed 0 (this should never occur) */ - return 0; -} - -int lvalexpr(svalue *sval) -{ - memset(sval, 0, sizeof(*sval)); - - errorset(sEXPRMARK, 0); - pushheaplist(); - sval->lvalue = hier14(&sval->val); - popheaplist(); - errorset(sEXPRRELEASE, 0); - - return sval->val.ident; -} - -int expression(cell *val,int *tag,symbol **symptr,int chkfuncresult,value *_lval) -{ - value lval={0}; - pushheaplist(); - - if (hier14(&lval)) - rvalue(&lval); - /* scrap any arrays left on the heap */ - popheaplist(); - - if (lval.ident==iCONSTEXPR && val!=NULL) /* constant expression */ - *val=lval.constval; - if (tag!=NULL) - *tag=lval.tag; - if (symptr!=NULL) - *symptr=lval.sym; - if (chkfuncresult) - checkfunction(&lval); - if (_lval) - *_lval=lval; - return lval.ident; -} - -int sc_getstateid(constvalue **automaton,constvalue **state) -{ - char name[sNAMEMAX+1]; - cell val; - char *str; - int fsa,islabel; - - assert(automaton!=NULL); - assert(state!=NULL); - if (!(islabel=matchtoken(tLABEL)) && !needtoken(tSYMBOL)) - return 0; - - tokeninfo(&val,&str); - assert(strlen(str)index>0); - assert(strlen(str)index==0); - } /* if */ - assert(*automaton!=NULL); - fsa=(*automaton)->index; - - assert(*automaton!=NULL); - *state=state_find(name,fsa); - if (*state==NULL) { - const char *fsaname=(*automaton)->name; - if (*fsaname=='\0') - fsaname="

"; - error(87,name,fsaname); /* unknown state for automaton */ - return 0; - } /* if */ - - return 1; -} - -cell array_totalsize(symbol *sym) -{ - cell length; - - assert(sym!=NULL); - assert(sym->ident==iARRAY || sym->ident==iREFARRAY); - length=sym->dim.array.length; - if (sym->dim.array.level > 0) { - cell sublength=array_totalsize(finddepend(sym)); - if (sublength>0) - length=length+length*sublength; - else - length=0; - } /* if */ - return length; -} - -static cell array_levelsize(symbol *sym,int level) -{ - assert(sym!=NULL); - assert(sym->ident==iARRAY || sym->ident==iREFARRAY); - assert(level <= sym->dim.array.level); - while (level-- > 0) { - sym=finddepend(sym); - assert(sym!=NULL); - } /* if */ - return (sym->dim.array.slength ? sym->dim.array.slength : sym->dim.array.length); -} - -/* hier14 - * - * Lowest hierarchy level (except for the , operator). - * - * Global references: sc_intest (reffered to only) - * sc_allowproccall (modified) - */ -static int hier14(value *lval1) -{ - int lvalue; - value lval2={0},lval3={0}; - void (*oper)(void); - int tok,level,i; - cell val; - char *st; - int bwcount,leftarray; - cell arrayidx1[sDIMEN_MAX],arrayidx2[sDIMEN_MAX]; /* last used array indices */ - cell *org_arrayidx; - - bwcount=bitwise_opercount; - bitwise_opercount=0; - /* initialize the index arrays with unlikely constant indices; note that - * these indices will only be changed when the array is indexed with a - * constant, and that negative array indices are invalid (so actually, any - * negative value would do). - */ - for (i=0; iarrayidx; /* save current pointer, to reset later */ - if (lval1->arrayidx==NULL) - lval1->arrayidx=arrayidx1; - lvalue=plnge1(hier13,lval1); - if (lval1->ident!=iARRAYCELL && lval1->ident!=iARRAYCHAR) - lval1->arrayidx=NULL; - if (lval1->ident==iCONSTEXPR) /* load constant here */ - ldconst(lval1->constval,sPRI); - tok=lex(&val,&st); - switch (tok) { - case taOR: - oper=ob_or; - break; - case taXOR: - oper=ob_xor; - break; - case taAND: - oper=ob_and; - break; - case taADD: - oper=ob_add; - break; - case taSUB: - oper=ob_sub; - break; - case taMULT: - oper=os_mult; - break; - case taDIV: - oper=os_div; - break; - case taMOD: - oper=os_mod; - break; - case taSHRU: - oper=ou_sar; - break; - case taSHR: - oper=os_sar; - break; - case taSHL: - oper=ob_sal; - break; - case '=': /* simple assignment */ - oper=NULL; - if (sc_intest) - error(211); /* possibly unintended assignment */ - break; - default: - lexpush(); - bitwise_opercount=bwcount; - lval1->arrayidx=org_arrayidx; /* restore array index pointer */ - return lvalue; - } /* switch */ - - /* if we get here, it was an assignment; first check a few special cases - * and then the general */ - if (lval1->ident==iARRAYCHAR) { - /* special case, assignment to packed character in a cell is permitted */ - lvalue=TRUE; - } else if (lval1->ident==iARRAY || lval1->ident==iREFARRAY) { - /* array assignment is permitted too (with restrictions) */ - if (oper) - return error(23); /* array assignment must be simple assigment */ - assert(lval1->sym!=NULL); - if (array_totalsize(lval1->sym)==0) - return error(46,lval1->sym->name); /* unknown array size */ - lvalue=TRUE; - } /* if */ - - /* operand on left side of assignment must be lvalue */ - if (!lvalue) - return error(22); /* must be lvalue */ - /* may not change "constant" parameters */ - assert(lval1->sym || lval1->accessor); - if (lval1->sym && (lval1->sym->usage & uCONST) != 0) - return error(22); /* assignment to const argument */ - sc_allowproccall=FALSE; /* may no longer use "procedure call" syntax */ - - lval3=*lval1; /* save symbol to enable storage of expresion result */ - lval1->arrayidx=org_arrayidx; /* restore array index pointer */ - if (lval1->ident==iARRAYCELL || lval1->ident==iARRAYCHAR - || lval1->ident==iARRAY || lval1->ident==iREFARRAY) - { - /* if indirect fetch: save PRI (cell address) */ - if (oper) { - pushreg(sPRI); - rvalue(lval1); - } /* if */ - lval2.arrayidx=arrayidx2; - plnge2(oper,hier14,lval1,&lval2); - if (lval2.ident!=iARRAYCELL && lval2.ident!=iARRAYCHAR) - lval2.arrayidx=NULL; - if (oper) - popreg(sALT); - if (!oper && lval3.arrayidx!=NULL && lval2.arrayidx!=NULL - && lval3.ident==lval2.ident && lval3.sym==lval2.sym) - { - int same=TRUE; - assert(lval2.arrayidx==arrayidx2); - for (i=0; iname); /* self-assignment */ - } /* if */ - } else if (lval1->ident == iACCESSOR) { - pushreg(sPRI); - if (oper) { - rvalue(lval1); - plnge2(oper,hier14,lval1,&lval2); - } else { - if (hier14(&lval2)) - rvalue(&lval2); /* instead of plnge2(). */ - else if (lval2.ident==iVARIABLE) - lval2.ident=iEXPRESSION;/* mark as "rvalue" if it is not an "lvalue" */ - checkfunction(&lval2); - } - popreg(sALT); - } else { - if (oper){ - rvalue(lval1); - plnge2(oper,hier14,lval1,&lval2); - } else { - /* if direct fetch and simple assignment: no "push" - * and "pop" needed -> call hier14() directly, */ - if (hier14(&lval2)) - rvalue(&lval2); /* instead of plnge2(). */ - else if (lval2.ident==iVARIABLE) - lval2.ident=iEXPRESSION;/* mark as "rvalue" if it is not an "lvalue" */ - checkfunction(&lval2); - /* check whether lval2 and lval3 (old lval1) refer to the same variable */ - if (lval2.ident==iVARIABLE && lval3.ident==lval2.ident && lval3.sym==lval2.sym) { - assert(lval3.sym!=NULL); - error(226,lval3.sym->name); /* self-assignment */ - } /* if */ - } /* if */ - } /* if */ - /* Array elements are sometimes considered as sub-arrays --when the - * array index is an enumeration field and the enumeration size is greater - * than 1. If the expression on the right side of the assignment is a cell, - * or if an operation is in effect, this does not apply. - */ - leftarray= lval3.ident==iARRAY || lval3.ident==iREFARRAY - || ((lval3.ident==iARRAYCELL || lval3.ident==iARRAYCHAR) - && lval3.constval>1 && lval3.sym->dim.array.level==0 - && !oper && (lval2.ident==iARRAY || lval2.ident==iREFARRAY)); - if (leftarray) { - /* Left operand is an array, right operand should be an array variable - * of the same size and the same dimension, an array literal (of the - * same size) or a literal string. For single-dimensional arrays without - * tag for the index, it is permitted to assign a smaller array into a - * larger one (without warning). This is to make it easier to work with - * strings. - */ - int exactmatch=TRUE; - int idxtag=0; - int ltlength=(int)lval3.sym->dim.array.length; - if ((lval3.ident==iARRAYCELL || lval3.ident==iARRAYCHAR) - && lval3.constval>0 && lval3.sym->dim.array.level==0) - { - ltlength=(int)lval3.constval; - } /* if */ - if (lval2.ident!=iARRAY && lval2.ident!=iREFARRAY - && (lval2.sym==NULL || lval2.constval<=0)) - error(33,lval3.sym->name); /* array must be indexed */ - if (lval2.sym!=NULL) { - if (lval2.constval==0) { - val=lval2.sym->dim.array.length;/* array variable */ - } else { - val=lval2.constval; - if (lval2.sym->dim.array.level!=0) - error(28,lval2.sym->name); - } /* if */ - level=lval2.sym->dim.array.level; - idxtag=lval2.sym->x.tags.index; - if (level==0 && idxtag==0 && lval3.sym->x.tags.index==0) - exactmatch=FALSE; - } else { - val=lval2.constval; /* literal array */ - level=0; - /* If val is negative, it means that lval2 is a literal string. - * The string array size may be smaller than the destination - * array, provided that the destination array does not have an - * index tag. - */ - if (val<0) { - val=-val; - if (lval3.sym->x.tags.index==0) - exactmatch=FALSE; - } /* if */ - } /* if */ - if (lval3.sym->dim.array.level!=level) - return error(47); /* array dimensions must match */ - else if (ltlengthval) || val==0) - return error(47); /* array sizes must match */ - else if (lval3.ident!=iARRAYCELL && !matchtag(lval3.sym->x.tags.index,idxtag,MATCHTAG_COERCE|MATCHTAG_SILENT)) - error(229,(lval2.sym!=NULL) ? lval2.sym->name : lval3.sym->name); /* index tag mismatch */ - if (level>0) { - /* check the sizes of all sublevels too */ - symbol *sym1 = lval3.sym; - symbol *sym2 = lval2.sym; - int i; - error(23); - assert(sym1!=NULL && sym2!=NULL); - /* ^^^ sym2 must be valid, because only variables can be - * multi-dimensional (there are no multi-dimensional literals), - * sym1 must be valid because it must be an lvalue - */ - assert(exactmatch); - for (i=0; idim.array.length!=sym2->dim.array.length) - error(47); /* array sizes must match */ - else if (!matchtag(sym1->x.tags.index,sym2->x.tags.index,MATCHTAG_COERCE|MATCHTAG_SILENT)) - error(229,sym2->name); /* index tag mismatch */ - } /* for */ - /* get the total size in cells of the multi-dimensional array */ - val=array_totalsize(lval3.sym); - assert(val>0); /* already checked */ - } /* if */ - } else { - /* left operand is not an array, right operand should then not be either */ - if (lval2.ident==iARRAY || lval2.ident==iREFARRAY) - error(6); /* must be assigned to an array */ - } /* if */ - if (leftarray) { - memcopy(val*sizeof(cell)); - } else { - check_userop(NULL,lval2.tag,lval3.tag,2,&lval3,&lval2.tag); - store(&lval3); /* now, store the expression result */ - } /* if */ - if (!oper && !checktag_string(&lval3, &lval2)) { - if ((lval3.tag == pc_tag_string && lval2.tag != pc_tag_string) || - (lval3.tag != pc_tag_string && lval2.tag == pc_tag_string)) - { - error(179, type_to_name(lval3.tag), type_to_name(lval2.tag)); - } else { - matchtag(lval3.tag,lval2.tag,TRUE); - } - } - if (lval3.sym) - markusage(lval3.sym,uWRITTEN); - sideeffect=TRUE; - bitwise_opercount=bwcount; - lval1->ident=iEXPRESSION; - return FALSE; /* expression result is never an lvalue */ -} - -/** - * Sums up array usage in the current heap tracer and convert it into a dynamic array. - * This is used for the ternary operator, which needs to convert its array usage into - * something dynamically managed. - * !Note: - * This might break if expressions can ever return dynamic arrays. - * Thus, we assert() if something is non-static here. - * Right now, this poses no problem because this type of expression is impossible: - * (a() ? return_array() : return_array()) ? return_array() : return_array() - */ - -long dynarray_from_heaplist(memuse_list_t *heap) -{ - memuse_t *use=heap->head; - memuse_t *tmp; - long total=0; - while (use) { - assert(use->type==MEMUSE_STATIC); - total+=use->size; - tmp=use->prev; - free(use); - use=tmp; - } - free(heap); - if (total) - setheap_save(-total*sizeof(cell)); - return total; -} - -static int hier13(value *lval) -{ - int lvalue=plnge1(hier12,lval); - if (matchtoken('?')) { - int flab1=getlabel(); - int flab2=getlabel(); - value lval2={0}; - int array1,array2; - long total1,total2; - memuse_list_t *heap; - - pushheaplist(); - if (lvalue) { - rvalue(lval); - } else if (lval->ident==iCONSTEXPR) { - ldconst(lval->constval,sPRI); - error(lval->constval ? 206 : 205); /* redundant test */ - } /* if */ - jmp_eq0(flab1); /* go to second expression if primary register==0 */ - PUSHSTK_I(sc_allowtags); - sc_allowtags=FALSE; /* do not allow tagnames here (colon is a special token) */ - if (hier13(lval)) - rvalue(lval); - if (lval->ident==iCONSTEXPR) /* load constant here */ - ldconst(lval->constval,sPRI); - sc_allowtags=(short)POPSTK_I(); /* restore */ - heap=popsaveheaplist(); - total1=dynarray_from_heaplist(heap); - pushheaplist(); - jumplabel(flab2); - setlabel(flab1); - needtoken(':'); - if (hier13(&lval2)) - rvalue(&lval2); - if (lval2.ident==iCONSTEXPR) /* load constant here */ - ldconst(lval2.constval,sPRI); - array1= (lval->ident==iARRAY || lval->ident==iREFARRAY); - array2= (lval2.ident==iARRAY || lval2.ident==iREFARRAY); - if (!array1 && array2) { - const char *ptr = "-unknown-"; - if (lval->sym != NULL) - ptr = lval->sym->name; - error(33,ptr); /* array must be indexed */ - } else if (array1 && !array2) { - const char *ptr = "-unknown-"; - if (lval2.sym != NULL) - ptr = lval2.sym->name; - error(33,ptr); /* array must be indexed */ - } /* if */ - /* ??? if both are arrays, should check dimensions */ - matchtag(lval->tag,lval2.tag,FALSE); - heap=popsaveheaplist(); - total2=dynarray_from_heaplist(heap); - setlabel(flab2); - if ((array1 && array2) && (total1 && total2)) { - markheap(MEMUSE_DYNAMIC, 0); - } - /* If both sides are arrays, we should return the maximal as the lvalue. - * Otherwise we could buffer overflow and the compiler is too stupid. - * Literal strings have a constval == -(num_cells) so the cmp is flipped. - */ - if (lval->ident==iARRAY && lval2.ident==iARRAY - && lval->constval < 0 - && lval->constval > lval2.constval) { - *lval = lval2; - } - if (lval->ident==iARRAY) - lval->ident=iREFARRAY; /* iARRAY becomes iREFARRAY */ - else if (lval->ident!=iREFARRAY) - lval->ident=iEXPRESSION; /* iREFARRAY stays iREFARRAY, rest becomes iEXPRESSION */ - return FALSE; /* conditional expression is no lvalue */ - } else { - return lvalue; - } /* if */ -} - -/* the order of the operators in these lists is important and must be - * the same as the order of the operators in the array "op1" - */ -static int list3[] = {'*','/','%',0}; -static int list4[] = {'+','-',0}; -static int list5[] = {tSHL,tSHR,tSHRU,0}; -static int list6[] = {'&',0}; -static int list7[] = {'^',0}; -static int list8[] = {'|',0}; -static int list9[] = {tlLE,tlGE,'<','>',0}; -static int list10[] = {tlEQ,tlNE,0}; -static int list11[] = {tlAND,0}; -static int list12[] = {tlOR,0}; - -static int hier12(value *lval) -{ - return skim(list12,jmp_ne0,1,0,hier11,lval); -} - -static int hier11(value *lval) -{ - return skim(list11,jmp_eq0,0,1,hier10,lval); -} - -static int hier10(value *lval) -{ /* ==, != */ - return plnge(list10,15,hier9,lval,"bool",TRUE); -} /* ^ this variable is the starting index in the op1[] - * array of the operators of this hierarchy level */ - -static int hier9(value *lval) -{ /* <=, >=, <, > */ - return plnge_rel(list9,11,hier8,lval); -} - -static int hier8(value *lval) -{ /* | */ - return plnge(list8,10,hier7,lval,NULL,FALSE); -} - -static int hier7(value *lval) -{ /* ^ */ - return plnge(list7,9,hier6,lval,NULL,FALSE); -} - -static int hier6(value *lval) -{ /* & */ - return plnge(list6,8,hier5,lval,NULL,FALSE); -} - -static int hier5(value *lval) -{ /* <<, >>, >>> */ - return plnge(list5,5,hier4,lval,NULL,FALSE); -} - -static int hier4(value *lval) -{ /* +, - */ - return plnge(list4,3,hier3,lval,NULL,FALSE); -} - -static int hier3(value *lval) -{ /* *, /, % */ - return plnge(list3,0,hier2,lval,NULL,FALSE); -} - -static int hier2(value *lval) -{ - int lvalue,tok; - int tag,paranthese; - cell val; - char *st; - symbol *sym; - int saveresult; - - tok=lex(&val,&st); - switch (tok) { - case tINC: /* ++lval */ - if (!hier2(lval)) - return error(22); /* must be lvalue */ - if (lval->ident != iACCESSOR) { - assert(lval->sym!=NULL); - if ((lval->sym->usage & uCONST)!=0) - return error(22); /* assignment to const argument */ - if (!check_userop(user_inc,lval->tag,0,1,lval,&lval->tag)) - inc(lval); /* increase variable first */ - rvalue(lval); /* and read the result into PRI */ - } else { - pushreg(sPRI); - invoke_getter(lval->accessor); - if (!check_userop(user_inc,lval->tag,0,1,lval,&lval->tag)) - inc_pri(); - popreg(sALT); - invoke_setter(lval->accessor, TRUE); - lval->ident = iEXPRESSION; - } - sideeffect=TRUE; - return FALSE; /* result is no longer lvalue */ - case tDEC: /* --lval */ - if (!hier2(lval)) - return error(22); /* must be lvalue */ - if (lval->ident != iACCESSOR) { - assert(lval->sym!=NULL); - if ((lval->sym->usage & uCONST)!=0) - return error(22); /* assignment to const argument */ - if (!check_userop(user_dec,lval->tag,0,1,lval,&lval->tag)) - dec(lval); /* decrease variable first */ - rvalue(lval); /* and read the result into PRI */ - } else { - pushreg(sPRI); - invoke_getter(lval->accessor); - if (!check_userop(user_dec,lval->tag,0,1,lval,&lval->tag)) - dec_pri(); - popreg(sALT); - invoke_setter(lval->accessor, TRUE); - lval->ident = iEXPRESSION; - } - sideeffect=TRUE; - return FALSE; /* result is no longer lvalue */ - case '~': /* ~ (one's complement) */ - if (hier2(lval)) - rvalue(lval); - invert(); /* bitwise NOT */ - lval->constval=~lval->constval; - return FALSE; - case '!': /* ! (logical negate) */ - if (hier2(lval)) - rvalue(lval); - if (check_userop(lneg,lval->tag,0,1,NULL,&lval->tag)) { - lval->ident=iEXPRESSION; - lval->constval=0; - } else { - lneg(); /* 0 -> 1, !0 -> 0 */ - lval->constval=!lval->constval; - lval->tag=pc_addtag("bool"); - } /* if */ - return FALSE; - case '-': /* unary - (two's complement) */ - if (hier2(lval)) - rvalue(lval); - /* make a special check for a constant expression with the tag of a - * rational number, so that we can simple swap the sign of that constant. - */ - if (lval->ident==iCONSTEXPR && lval->tag==sc_rationaltag && sc_rationaltag!=0) { - if (rational_digits==0) { - #if PAWN_CELL_SIZE==32 - float *f = (float *)&lval->constval; - #elif PAWN_CELL_SIZE==64 - double *f = (double *)&lval->constval; - #else - #error Unsupported cell size - #endif - *f= - *f; /* this modifies lval->constval */ - } else { - /* the negation of a fixed point number is just an integer negation */ - lval->constval=-lval->constval; - } /* if */ - } else if (check_userop(neg,lval->tag,0,1,NULL,&lval->tag)) { - lval->ident=iEXPRESSION; - lval->constval=0; - } else { - neg(); /* arithmic negation */ - lval->constval=-lval->constval; - } /* if */ - return FALSE; - case tNEW: /* call nullable methodmap constructor */ - { - tok = lex(&val, &st); - if (tok != tSYMBOL) - return error(20, st); /* illegal symbol name */ - - symbol *target = NULL; - methodmap_t *methodmap = methodmap_find_by_name(st); - if (!methodmap) - error(116, st); - else if (!methodmap->nullable) - error(171, methodmap->name); - else if (!methodmap->ctor) - error(172, methodmap->name); - else - target = methodmap->ctor->target; - - if (!target) { - needtoken('('); - int depth = 1; - // Eat tokens until we get a newline or EOF or ')' or ';' - while (true) { - if (peek_same_line() == tEOL) - return FALSE; - if ((tok = lex(&val, &st)) == 0) - return FALSE; - if (tok == ')') { - if (--depth == 0) - return FALSE; - } - if (tok == ';') - return FALSE; - if (tok == '(') - depth++; - } - } - - needtoken('('); - callfunction(target, NULL, lval, TRUE); - return FALSE; - } - case tVIEW_AS: /* newer tagname override */ - { - needtoken('<'); - int tag = 0; - { - token_t tok; - lextok(&tok); - if (!parse_new_typename(&tok, &tag)) - tag = 0; - } - needtoken('>'); - - if (tag == pc_tag_void) - error(144); - - lval->cmptag = tag; - lvalue = hier12(lval); - - if ((lval->tag & OBJECTTAG) || (tag & OBJECTTAG)) { - matchtag(tag, lval->tag, MATCHTAG_COERCE); - } else if ((tag & FUNCTAG) != (lval->tag & FUNCTAG)) { - // Warn: unsupported cast. - error(237); - } - lval->tag = tag; - return lvalue; - } - case tLABEL: /* tagname override */ - tag=pc_addtag(st); - if (sc_require_newdecls) { - // Warn: old style cast used when newdecls pragma is enabled - error(240, st, type_to_name(tag)); - } - lval->cmptag=tag; - lvalue=hier2(lval); - if ((lval->tag & OBJECTTAG) || (tag & OBJECTTAG)) { - matchtag(tag, lval->tag, MATCHTAG_COERCE); - } else if ((tag & FUNCTAG) != (lval->tag & FUNCTAG)) { - // Warn: unsupported cast. - error(237); - } - lval->tag=tag; - return lvalue; - case tDEFINED: - paranthese=0; - while (matchtoken('(')) - paranthese++; - tok=lex(&val,&st); - if (tok!=tSYMBOL) - return error(20,st); /* illegal symbol name */ - sym=findloc(st); - if (sym==NULL) - sym=findglb(st,sSTATEVAR); - if (sym!=NULL && sym->ident!=iFUNCTN && sym->ident!=iREFFUNC && (sym->usage & uDEFINE)==0) - sym=NULL; /* symbol is not a function, it is in the table, but not "defined" */ - val= (sym!=NULL); - if (!val && find_subst(st,strlen(st))!=NULL) - val=1; - clear_value(lval); - lval->ident=iCONSTEXPR; - lval->constval= val; - lval->tag=pc_addtag("bool"); - ldconst(lval->constval,sPRI); - while (paranthese--) - needtoken(')'); - return FALSE; - case tSIZEOF: - paranthese=0; - while (matchtoken('(')) - paranthese++; - tok=lex(&val,&st); - if (tok!=tSYMBOL) - return error(20,st); /* illegal symbol name */ - sym=findloc(st); - if (sym==NULL) - sym=findglb(st,sSTATEVAR); - if (sym==NULL) - return error(17,st); /* undefined symbol */ - if (sym->ident==iCONSTEXPR) - error(39); /* constant symbol has no size */ - else if (sym->ident==iFUNCTN || sym->ident==iREFFUNC) - error(72); /* "function" symbol has no size */ - else if ((sym->usage & uDEFINE)==0) - return error(17,st); /* undefined symbol (symbol is in the table, but it is "used" only) */ - clear_value(lval); - lval->ident=iCONSTEXPR; - lval->constval=1; /* preset */ - markusage(sym, uREAD); - if (sym->ident==iARRAY || sym->ident==iREFARRAY) { - int level; - symbol *idxsym=NULL; - symbol *subsym=sym; - for (level=0; matchtoken('['); level++) { - idxsym=NULL; - if (subsym!=NULL && level==subsym->dim.array.level && matchtoken(tSYMBOL)) { - char *idxname; - int cmptag=subsym->x.tags.index; - tokeninfo(&val,&idxname); - if ((idxsym=findconst(idxname,&cmptag))==NULL) - error(80,idxname); /* unknown symbol, or non-constant */ - else if (cmptag>1) - error(91,idxname); /* ambiguous constant */ - } /* if */ - needtoken(']'); - if (subsym!=NULL) - subsym=finddepend(subsym); - } /* for */ - if (level>sym->dim.array.level+1) { - error(28,sym->name); /* invalid subscript */ - } else if (level==sym->dim.array.level+1) { - lval->constval=(idxsym!=NULL && idxsym->dim.array.length>0) ? idxsym->dim.array.length : 1; - } else { - lval->constval=array_levelsize(sym,level); - } - if (lval->constval==0 && strchr((char *)lptr,PREPROC_TERM)==NULL) - error(163,st); /* indeterminate array size in "sizeof" expression */ - } /* if */ - ldconst(lval->constval,sPRI); - while (paranthese--) - needtoken(')'); - return FALSE; - case tCELLSOF: - paranthese=0; - while (matchtoken('(')) - paranthese++; - tok=lex(&val,&st); - if (tok!=tSYMBOL) - return error(20,st); /* illegal symbol name */ - sym=findloc(st); - if (sym==NULL) - sym=findglb(st,sSTATEVAR); - if (sym==NULL) - return error(17,st); /* undefined symbol */ - if (sym->ident==iCONSTEXPR) - error(39); /* constant symbol has no size */ - else if (sym->ident==iFUNCTN || sym->ident==iREFFUNC) - error(72); /* "function" symbol has no size */ - else if ((sym->usage & uDEFINE)==0) - return error(17,st); /* undefined symbol (symbol is in the table, but it is "used" only) */ - clear_value(lval); - lval->ident=iCONSTEXPR; - lval->constval=1; /* preset */ - if (sym->ident==iARRAY || sym->ident==iREFARRAY) { - int level; - symbol *idxsym=NULL; - symbol *subsym=sym; - for (level=0; matchtoken('['); level++) { - idxsym=NULL; - if (subsym!=NULL && level==subsym->dim.array.level && matchtoken(tSYMBOL)) { - char *idxname; - int cmptag=subsym->x.tags.index; - tokeninfo(&val,&idxname); - if ((idxsym=findconst(idxname,&cmptag))==NULL) - error(80,idxname); /* unknown symbol, or non-constant */ - else if (cmptag>1) - error(91,idxname); /* ambiguous constant */ - } /* if */ - needtoken(']'); - if (subsym!=NULL) - subsym=finddepend(subsym); - } /* for */ - if (level>sym->dim.array.level+1) { - error(28,sym->name); /* invalid subscript */ - } else if (level==sym->dim.array.level+1) { - lval->constval= (idxsym!=NULL && idxsym->dim.array.length>0) ? idxsym->dim.array.length : 1; - } else { - lval->constval=array_levelsize(sym,level); - } - if (lval->constval==0 && strchr((char *)lptr,PREPROC_TERM)==NULL) - error(163,st); /* indeterminate array size in "sizeof" expression */ - } /* if */ - ldconst(lval->constval,sPRI); - while (paranthese--) - needtoken(')'); - return FALSE; - case tTAGOF: - paranthese=0; - while (matchtoken('(')) - paranthese++; - tok=lex(&val,&st); - if (tok!=tSYMBOL && tok!=tLABEL) - return error(20,st); /* illegal symbol name */ - if (tok==tLABEL) { - constvalue *tagsym=find_constval(&tagname_tab,st,0); - tag=(int)((tagsym!=NULL) ? tagsym->value : 0); - } else { - sym=findloc(st); - if (sym==NULL) - sym=findglb(st,sSTATEVAR); - if (sym==NULL) - return error(17,st); /* undefined symbol */ - if ((sym->usage & uDEFINE)==0) - return error(17,st); /* undefined symbol (symbol is in the table, but it is "used" only) */ - tag=sym->tag; - } /* if */ - if (sym->ident==iARRAY || sym->ident==iREFARRAY) { - int level; - symbol *idxsym=NULL; - symbol *subsym=sym; - for (level=0; matchtoken('['); level++) { - idxsym=NULL; - if (subsym!=NULL && level==subsym->dim.array.level && matchtoken(tSYMBOL)) { - char *idxname; - int cmptag=subsym->x.tags.index; - tokeninfo(&val,&idxname); - if ((idxsym=findconst(idxname,&cmptag))==NULL) - error(80,idxname); /* unknown symbol, or non-constant */ - else if (cmptag>1) - error(91,idxname); /* ambiguous constant */ - } /* if */ - needtoken(']'); - if (subsym!=NULL) - subsym=finddepend(subsym); - } /* for */ - if (level>sym->dim.array.level+1) - error(28,sym->name); /* invalid subscript */ - else if (level==sym->dim.array.level+1 && idxsym!=NULL) - tag= idxsym->x.tags.index; - } /* if */ - clear_value(lval); - lval->ident=iCONSTEXPR; - lval->constval=tag; - ldconst(lval->constval,sPRI); - while (paranthese--) - needtoken(')'); - return FALSE; - default: - lexpush(); - lvalue=hier1(lval); - /* check for postfix operators */ - if (matchtoken(';')) { - /* Found a ';', do not look further for postfix operators */ - lexpush(); /* push ';' back after successful match */ - return lvalue; - } else if (matchtoken(tTERM)) { - /* Found a newline that ends a statement (this is the case when - * semicolons are optional). Note that an explicit semicolon was - * handled above. This case is similar, except that the token must - * not be pushed back. - */ - return lvalue; - } else { - tok=lex(&val,&st); - switch (tok) { - case tINC: /* lval++ */ - if (!lvalue) - return error(22); /* must be lvalue */ - if (lval->ident != iACCESSOR) { - assert(lval->sym!=NULL); - if ((lval->sym->usage & uCONST)!=0) - return error(22); /* assignment to const argument */ - /* on incrementing array cells, the address in PRI must be saved for - * incremening the value, whereas the current value must be in PRI - * on exit. - */ - saveresult= (lval->ident==iARRAYCELL || lval->ident==iARRAYCHAR); - if (saveresult) - pushreg(sPRI); /* save address in PRI */ - rvalue(lval); /* read current value into PRI */ - if (saveresult) - swap1(); /* save PRI on the stack, restore address in PRI */ - if (!check_userop(user_inc,lval->tag,0,1,lval,&lval->tag)) - inc(lval); /* increase variable afterwards */ - if (saveresult) - popreg(sPRI); /* restore PRI (result of rvalue()) */ - } else { - pushreg(sPRI); // save obj - invoke_getter(lval->accessor); - move_alt(); // alt = oldval - swap1(); // pri = saved obj, stack = [oldval] - pushreg(sPRI); // pri = obj, alt = oldval, stack = [obj, oldval] - moveto1(); // pri = oldval, stack = [obj, oldval] - - // check_userop on an iACCESSOR acts as though the value is an rvalue. - if (!check_userop(user_inc, lval->tag, 0, 1, lval, &lval->tag)) - inc_pri(); - - popreg(sALT); - invoke_setter(lval->accessor, FALSE); - popreg(sPRI); - lval->ident = iEXPRESSION; - } - sideeffect=TRUE; - return FALSE; /* result is no longer lvalue */ - case tDEC: /* lval-- */ - if (!lvalue) - return error(22); /* must be lvalue */ - if (lval->ident != iACCESSOR) { - assert(lval->sym!=NULL); - if ((lval->sym->usage & uCONST)!=0) - return error(22); /* assignment to const argument */ - saveresult= (lval->ident==iARRAYCELL || lval->ident==iARRAYCHAR); - if (saveresult) - pushreg(sPRI); /* save address in PRI */ - rvalue(lval); /* read current value into PRI */ - if (saveresult) - swap1(); /* save PRI on the stack, restore address in PRI */ - if (!check_userop(user_dec,lval->tag,0,1,lval,&lval->tag)) - dec(lval); /* decrease variable afterwards */ - if (saveresult) - popreg(sPRI); /* restore PRI (result of rvalue()) */ - } else { - pushreg(sPRI); // save obj - invoke_getter(lval->accessor); - move_alt(); // alt = oldval - swap1(); // pri = saved obj, stack = [oldval] - pushreg(sPRI); // pri = obj, alt = oldval, stack = [obj, oldval] - moveto1(); // pri = oldval, stack = [obj, oldval] - - // check_userop on an iACCESSOR acts as though the value is an rvalue. - if (!check_userop(user_dec, lval->tag, 0, 1, lval, &lval->tag)) - dec_pri(); - - popreg(sALT); - invoke_setter(lval->accessor, FALSE); - popreg(sPRI); - lval->ident = iEXPRESSION; - } - sideeffect=TRUE; - return FALSE; -/* This is temporarily disabled because we detect it automatically. - * Thus, it could be weird if both were used at once - */ -#if 0 - case tCHAR: /* char (compute required # of cells */ - if (lval->ident==iCONSTEXPR) { - lval->constval *= sCHARBITS/8; /* from char to bytes */ - lval->constval = (lval->constval + sizeof(cell)-1) / sizeof(cell); - } else { - if (lvalue) - rvalue(lval); /* fetch value if not already in PRI */ - char2addr(); /* from characters to bytes */ - addconst(sizeof(cell)-1); /* make sure the value is rounded up */ - addr2cell(); /* truncate to number of cells */ - } /* if */ - return FALSE; -#endif - default: - lexpush(); - return lvalue; - } /* switch */ - } /* if */ - } /* switch */ -} - -static symbol * -fake_function_for_method(methodmap_t *map, const char *lexstr) -{ - // Fetch a fake function so errors aren't as crazy. - char tmpname[METHOD_NAMEMAX + 1]; - strcpy(tmpname, map->name); - strcat(tmpname, "."); - strcat(tmpname, lexstr); - tmpname[sNAMEMAX] = '\0'; - return fetchfunc(tmpname); -} - -enum FieldExprResult -{ - FER_Fail, - FER_Accessor, - FER_CallFunction, - FER_CallMethod -}; - -static FieldExprResult -field_expression(svalue &thisval, value *lval, symbol **target) -{ - // Catch invalid calls early so we don't compile with a tag mismatch. - switch (thisval.val.ident) { - case iARRAY: - case iREFARRAY: - error(106); - break; - - case iFUNCTN: - case iREFFUNC: - error(107); - break; - } - - cell lexval; - char *lexstr; - if (!needtoken(tSYMBOL)) - return FER_Fail; - tokeninfo(&lexval, &lexstr); - - if (thisval.val.ident == iMETHODMAP) { - methodmap_t *map = thisval.val.sym->methodmap; - methodmap_method_t *method = methodmap_find_method(map, lexstr); - if (!method) { - error(105, map->name, lexstr); - *target = fake_function_for_method(map, lexstr); - return FER_CallFunction; - } - - if (!method->is_static) - error(176, method->name, map->name); - *target = method->target; - return FER_CallFunction; - } - - methodmap_t *map; - if ((map = methodmap_find_by_tag(thisval.val.tag)) == NULL) { - error(104, pc_tagname(thisval.val.tag)); - return FER_Fail; - } - - methodmap_method_t *method; - if ((method = methodmap_find_method(map, lexstr)) == NULL) { - error(105, map->name, lexstr); - *target = fake_function_for_method(map, lexstr); - return FER_CallFunction; - } - - if (method && (method->getter || method->setter)) { - if (thisval.lvalue) - rvalue(lval); - clear_value(lval); - lval->ident = iACCESSOR; - lval->tag = method->property_tag(); - lval->accessor = method; - return FER_Accessor; - } - - *target = method->target; - - if (method->is_static) { - error(177, method->name, map->name, method->name); - return FER_CallFunction; - } - return FER_CallMethod; -} - - -/* hier1 - * - * The highest hierarchy level: it looks for pointer and array indices - * and function calls. - * Generates code to fetch a pointer value if it is indexed and code to - * add to the pointer value or the array address (the address is already - * read at primary()). It also generates code to fetch a function address - * if that hasn't already been done at primary() (check lval[4]) and calls - * callfunction() to call the function. - */ -static int hier1(value *lval1) -{ - int lvalue,index,tok,symtok; - cell val,cidx; - value lval2={0}; - char *st; - char close; - symbol *sym; - int magic_string=0; - symbol dummysymbol,*cursym; /* for changing the index tags in case of enumerated pseudo-arrays */ - - lvalue=primary(lval1); - symtok=tokeninfo(&val,&st); /* get token read by primary() */ - cursym=lval1->sym; - -restart: - sym=cursym; - - if (lval1->ident == iMETHODMAP && - !(lexpeek('.') || lexpeek('('))) - { - // Cannot use methodmap as an rvalue/lvalue. - error(174, sym ? sym->name : "(unknown)"); - - lval1->ident = iCONSTEXPR; - lval1->tag = 0; - lval1->constval = 0; - } - - if (matchtoken('[') || matchtoken('{') || matchtoken('(') || matchtoken('.')) { - tok=tokeninfo(&val,&st); /* get token read by matchtoken() */ - if (lvalue && lval1->ident == iACCESSOR) { - rvalue(lval1); - lvalue = FALSE; - } - magic_string = (sym && (sym->tag == pc_tag_string && sym->dim.array.level == 0)); - if (sym==NULL && symtok!=tSYMBOL) { - /* we do not have a valid symbol and we appear not to have read a valid - * symbol name (so it is unlikely that we would have read a name of an - * undefined symbol) */ - error(29); /* expression error, assumed 0 */ - lexpush(); /* analyse '(', '{' or '[' again later */ - return FALSE; - } /* if */ - if (tok=='[' || tok=='{') { /* subscript */ - close = (char)((tok=='[') ? ']' : '}'); - if (sym==NULL) { /* sym==NULL if lval is a constant or a literal */ - error(28,""); /* cannot subscript */ - needtoken(close); - return FALSE; - } else if (sym->ident!=iARRAY && sym->ident!=iREFARRAY){ - error(28,sym->name); /* cannot subscript, variable is not an array */ - needtoken(close); - return FALSE; - } else if (sym->dim.array.level>0 && close!=']') { - error(51); /* invalid subscript, must use [ ] */ - needtoken(close); - return FALSE; - } /* if */ - /* set the tag to match (enumeration fields as indices) */ - lval2.cmptag=sym->x.tags.index; - stgget(&index,&cidx); /* mark position in code generator */ - pushreg(sPRI); /* save base address of the array */ - if (hier14(&lval2)) /* create expression for the array index */ - rvalue(&lval2); - if (lval2.ident==iARRAY || lval2.ident==iREFARRAY) - error(33,lval2.sym->name); /* array must be indexed */ - needtoken(close); - if ((sym->usage & uENUMROOT)) - matchtag(sym->x.tags.index,lval2.tag,TRUE); - if (lval2.ident==iCONSTEXPR) { /* constant expression */ - stgdel(index,cidx); /* scratch generated code */ - if (lval1->arrayidx!=NULL) { /* keep constant index, for checking */ - assert(sym->dim.array.level>=0 && sym->dim.array.levelarrayidx[sym->dim.array.level]=lval2.constval; - } /* if */ - if (close==']' && !(sym->tag == pc_tag_string && sym->dim.array.level == 0)) { - /* normal array index */ - if (lval2.constval<0 || (sym->dim.array.length!=0 && sym->dim.array.length<=lval2.constval)) - error(32,sym->name); /* array index out of bounds */ - if (lval2.constval!=0) { - /* don't add offsets for zero subscripts */ - #if PAWN_CELL_SIZE==16 - ldconst(lval2.constval<<1,sALT); - #elif PAWN_CELL_SIZE==32 - ldconst(lval2.constval<<2,sALT); - #elif PAWN_CELL_SIZE==64 - ldconst(lval2.constval<<3,sALT); - #else - #error Unsupported cell size - #endif - ob_add(); - } /* if */ - } else { - /* character index */ - if (lval2.constval<0 || (sym->dim.array.length!=0 - && sym->dim.array.length*((8*sizeof(cell))/sCHARBITS)<=(ucell)lval2.constval)) - error(32,sym->name); /* array index out of bounds */ - if (lval2.constval!=0) { - /* don't add offsets for zero subscripts */ - #if sCHARBITS==16 - ldconst(lval2.constval<<1,sALT);/* 16-bit character */ - #else - ldconst(lval2.constval,sALT); /* 8-bit character */ - #endif - ob_add(); - } /* if */ - charalign(); /* align character index into array */ - } /* if */ - /* if the array index is a field from an enumeration, get the tag name - * from the field and save the size of the field too. - */ - assert(lval2.sym==NULL || lval2.sym->dim.array.level==0); - if (lval2.sym && - lval2.sym->parent && - lval2.sym->dim.array.length > 0 && - sym->dim.array.level==0) - { - lval1->tag=lval2.sym->x.tags.index; - lval1->constval=lval2.sym->dim.array.length; - } /* if */ - } else { - /* array index is not constant */ - lval1->arrayidx=NULL; /* reset, so won't be checked */ - if (close==']' && !magic_string) { - if (sym->dim.array.length!=0) - ffbounds(sym->dim.array.length-1); /* run time check for array bounds */ - cell2addr(); /* normal array index */ - } else { - if (sym->dim.array.length!=0) - ffbounds(sym->dim.array.length*(32/sCHARBITS)-1); - char2addr(); /* character array index */ - } /* if */ - popreg(sALT); - ob_add(); /* base address was popped into secondary register */ - if (close!=']' || magic_string) - charalign(); /* align character index into array */ - } /* if */ - /* the indexed item may be another array (multi-dimensional arrays) */ - assert(cursym==sym && sym!=NULL); /* should still be set */ - if (sym->dim.array.level>0) { - assert(close==']'); /* checked earlier */ - assert(cursym==lval1->sym); - /* read the offset to the subarray and add it to the current address */ - lval1->ident=iARRAYCELL; - pushreg(sPRI); /* the optimizer makes this to a MOVE.alt */ - rvalue(lval1); - popreg(sALT); - ob_add(); - /* adjust the "value" structure and find the referenced array */ - lval1->ident=iREFARRAY; - lval1->sym=finddepend(sym); - assert(lval1->sym!=NULL); - assert(lval1->sym->dim.array.level==sym->dim.array.level-1); - cursym=lval1->sym; - /* try to parse subsequent array indices */ - lvalue=FALSE; /* for now, a iREFARRAY is no lvalue */ - goto restart; - } /* if */ - assert(sym->dim.array.level==0); - /* set type to fetch... INDIRECTLY */ - if (sym->tag == pc_tag_string) { - lval1->ident = iARRAYCHAR; - } else { - lval1->ident= (char)((close==']') ? iARRAYCELL : iARRAYCHAR); - } - /* if the array index is a field from an enumeration, get the tag name - * from the field and save the size of the field too. Otherwise, the - * tag is the one from the array symbol. - */ - if (lval2.ident==iCONSTEXPR && - lval2.sym && - lval2.sym->parent && - lval2.sym->dim.array.length > 0 && - sym->dim.array.level == 0) - { - lval1->tag=lval2.sym->x.tags.index; - lval1->constval=lval2.sym->dim.array.length; - if (lval2.tag==sym->x.tags.index && lval1->constval>1 && matchtoken('[')) { - /* an array indexed with an enumeration field may be considered a sub-array */ - lexpush(); - lvalue=FALSE; /* for now, a iREFARRAY is no lvalue */ - lval1->ident=iREFARRAY; - /* initialize a dummy symbol, which is a copy of the current symbol, - * but with an adjusted index tag - */ - assert(sym!=NULL); - dummysymbol=*sym; - /* get the tag of the root of the enumeration */ - assert(lval2.sym!=NULL); - dummysymbol.x.tags.index=lval2.sym->x.tags.field; - dummysymbol.dim.array.length=lval2.sym->dim.array.length; - cursym=&dummysymbol; - /* recurse */ - goto restart; - } /* if */ - } else { - assert(sym!=NULL); - if (cursym!=&dummysymbol) - lval1->tag=sym->tag; - lval1->constval=0; - } /* if */ - - /* a cell in an array is an lvalue, a character in an array is not - * always a *valid* lvalue */ - lvalue = TRUE; - - // If there's a call/fetch coming up, keep parsing. - if (matchtoken('.')) { - lexpush(); - goto restart; - } - - return lvalue; - } else { /* tok=='(' -> function(...) */ - svalue thisval; - thisval.val = *lval1; - thisval.lvalue = lvalue; - - svalue *implicitthis = NULL; - if (tok == '.') { - switch (field_expression(thisval, lval1, &sym)) { - case FER_Fail: - case FER_CallFunction: - break; - case FER_CallMethod: - implicitthis = &thisval; - break; - case FER_Accessor: - lvalue = TRUE; - goto restart; - default: - assert(false); - } - - // If we don't find a '(' next, just fail to compile for now -- and - // don't even try to do a function call, just restart the parse loop. - if (!needtoken('(')) - goto restart; - - tok = '('; - } - - assert(tok=='('); - if (sym==NULL || (sym->ident!=iFUNCTN && sym->ident!=iREFFUNC)) { - if (sym && sym->ident == iMETHODMAP && sym->methodmap) { - if (!sym->methodmap->ctor) { - // Immediately fatal - no function to call. - return error(172, sym->name); - } - if (sym->methodmap->nullable) { - // Keep going, this is basically a style thing. - error(170, sym->methodmap->name); - } - - sym = sym->methodmap->ctor->target; - } else if (sym==NULL && sc_status==statFIRST) { - /* could be a "use before declaration"; in that case, create a stub - * function so that the usage can be marked. - */ - sym=fetchfunc(lastsymbol); - if (sym==NULL) - error(FATAL_ERROR_OOM); - markusage(sym,uREAD); - } else { - return error(12); /* invalid function call */ - } - } else if ((sym->usage & uMISSING)!=0) { - char symname[2*sNAMEMAX+16]; /* allow space for user defined operators */ - funcdisplayname(symname,sym->name); - error(4,symname); /* function not defined */ - } /* if */ - - callfunction(sym,implicitthis,lval1,TRUE); - if (lexpeek('.')) { - lvalue = FALSE; - goto restart; - } - return FALSE; /* result of function call is no lvalue */ - } /* if */ - } /* if */ - if (sym!=NULL && lval1->ident==iFUNCTN) { - assert(sym->ident==iFUNCTN); - - if (sym->usage & uNATIVE) { - error(76); - return FALSE; - } - if (finddepend(sym)) { - error(182); - return FALSE; - } - - funcenum_t *fe = funcenum_for_symbol(sym); - - // Get address into pri. - load_glbfn(sym); - - // New-style "closure". - lval1->sym = NULL; - lval1->ident = iEXPRESSION; - lval1->constval = 0; - lval1->tag = fe->tag; - return FALSE; - } /* if */ - return lvalue; -} - -/* primary - * - * Returns 1 if the operand is an lvalue (everything except arrays, functions - * constants and -of course- errors). - * Generates code to fetch the address of arrays. Code for constants is - * already generated by constant(). - * This routine first clears the entire lval array (all fields are set to 0). - * - * Global references: sc_intest (may be altered, but restored upon termination) - */ -static int primary(value *lval) -{ - char *st; - int lvalue,tok; - cell val; - symbol *sym; - - if (matchtoken('(')){ /* sub-expression - (expression,...) */ - PUSHSTK_I(sc_intest); - PUSHSTK_I(sc_allowtags); - - sc_intest=FALSE; /* no longer in "test" expression */ - sc_allowtags=TRUE; /* allow tagnames to be used in parenthesized expressions */ - sc_allowproccall=FALSE; - do - lvalue=hier14(lval); - while (matchtoken(',')); - needtoken(')'); - lexclr(FALSE); /* clear lex() push-back, it should have been - * cleared already by needtoken() */ - sc_allowtags=(short)POPSTK_I(); - sc_intest=(short)POPSTK_I(); - return lvalue; - } /* if */ - - clear_value(lval); /* clear lval */ - tok=lex(&val,&st); - - if (tok == tTHIS) { - strcpy(lastsymbol, "this"); - if ((sym = findloc("this")) == NULL) { - error(166); /* 'this' outside method body */ - ldconst(0, sPRI); - return FALSE; - } - - assert(sym->ident == iVARIABLE); - lval->sym = sym; - lval->ident = sym->ident; - lval->tag = sym->tag; - return TRUE; - } - - if (tok==tSYMBOL) { - /* lastsymbol is char[sNAMEMAX+1], lex() should have truncated any symbol - * to sNAMEMAX significant characters */ - assert(strlen(st)ident==iLABEL) { - error(29); /* expression error, assumed 0 */ - ldconst(0,sPRI); /* load 0 */ - return FALSE; /* return 0 for labels (expression error) */ - } /* if */ - lval->sym=sym; - lval->ident=sym->ident; - lval->tag=sym->tag; - if (sym->ident==iARRAY || sym->ident==iREFARRAY) { - address(sym,sPRI); /* get starting address in primary register */ - return FALSE; /* return 0 for array (not lvalue) */ - } else { - return TRUE; /* return 1 if lvalue (not label or array) */ - } /* if */ - } /* if */ - /* now try a global variable */ - if ((sym = findglb(st, sSTATEVAR)) != 0) { - if (sym->ident==iFUNCTN || sym->ident==iREFFUNC) { - /* if the function is only in the table because it was inserted as a - * stub in the first pass (i.e. it was "used" but never declared or - * implemented, issue an error - */ - if ((sym->usage & uPROTOTYPED)==0) - error(17,st); - } else { - if ((sym->usage & uDEFINE)==0) - error(17,st); - lval->sym=sym; - lval->ident=sym->ident; - lval->tag=sym->tag; - switch (sym->ident) { - case iARRAY: - case iREFARRAY: - address(sym,sPRI); /* get starting address in primary register */ - return FALSE; /* return 0 for array (not lvalue) */ - case iMETHODMAP: - return FALSE; - default: - return TRUE; /* return 1 if lvalue (not function or array) */ - } /* switch */ - } /* if */ - } else { - if (!sc_allowproccall) - return error(17,st); /* undefined symbol */ - /* an unknown symbol, but used in a way compatible with the "procedure - * call" syntax. So assume that the symbol refers to a function. - */ - assert(sc_status==statFIRST); - sym=fetchfunc(st); - if (sym==NULL) - error(FATAL_ERROR_OOM); - } /* if */ - assert(sym!=NULL); - assert(sym->ident==iFUNCTN || sym->ident==iREFFUNC); - lval->sym=sym; - lval->ident=sym->ident; - lval->tag=sym->tag; - return FALSE; /* return 0 for function (not an lvalue) */ - } /* if */ - lexpush(); /* push the token, it is analyzed by constant() */ - if (constant(lval)==0) { - error(29); /* expression error, assumed 0 */ - ldconst(0,sPRI); /* load 0 */ - } /* if */ - return FALSE; /* return 0 for constants (or errors) */ -} - -static void clear_value(value *lval) -{ - lval->sym=NULL; - lval->constval=0L; - lval->tag=0; - lval->ident=0; - lval->boolresult=FALSE; - lval->accessor=NULL; - /* do not clear lval->arrayidx, it is preset in hier14() */ - /* do not clear lval->cmptag */ -} - -static void setdefarray(cell *string,cell size,cell array_sz,cell *dataaddr,int fconst) -{ - /* The routine must copy the default array data onto the heap, as to avoid - * that a function can change the default value. An optimization is that - * the default array data is "dumped" into the data segment only once (on the - * first use). - */ - /* check whether to dump the default array */ - assert(dataaddr!=NULL); - if (sc_status==statWRITE && *dataaddr<0) { - int i; - *dataaddr=(litidx+glb_declared)*sizeof(cell); - for (i=0; i=size); - modheap((int)array_sz*sizeof(cell)); - markheap(MEMUSE_STATIC, array_sz); - /* ??? should perhaps fill with zeros first */ - memcopy(size*sizeof(cell)); - moveto1(); - } /* if */ -} - -static int findnamedarg(arginfo *arg,char *name) -{ - int i; - - for (i=0; arg[i].ident!=0 && arg[i].ident!=iVARARGS; i++) - if (strcmp(arg[i].name,name)==0) - return i; - return -1; -} - -int checktag(int tags[],int numtags,int exprtag) -{ - int i; - int errcount = errnum; - - if (numtags > 1 && (exprtag & OBJECTTAG)) { - // This would allow leaking of the pointer, unless we verify that all tags - // are object tags. It's easiest to just forbid this. The feature is broken - // anyway since there is no way to determine the actual value's type. - error(135); - return FALSE; - } - - assert(tags!=0); - assert(numtags>0); - for (i=0; iident=iEXPRESSION; /* preset, may be changed later */ - lval_result->constval=0; - lval_result->tag=sym->tag; - /* check whether this is a function that returns an array */ - symret=finddepend(sym); - assert(symret==NULL || symret->ident==iREFARRAY); - if (symret!=NULL) { - int retsize; - /* allocate space on the heap for the array, and pass the pointer to the - * reserved memory block as a hidden parameter - */ - retsize=(int)array_totalsize(symret); - assert(retsize>0); - modheap(retsize*sizeof(cell));/* address is in ALT */ - pushreg(sALT); /* pass ALT as the last (hidden) parameter */ - markheap(MEMUSE_STATIC, retsize); - /* also mark the ident of the result as "array" */ - lval_result->ident=iREFARRAY; - lval_result->sym=symret; - } /* if */ - pushheaplist(); - - nesting++; - assert(nest_stkusage>=0); - #if !defined NDEBUG - if (nesting==1) - assert(nest_stkusage==0); - #endif - sc_allowproccall=FALSE; /* parameters may not use procedure call syntax */ - - if ((sym->flags & flgDEPRECATED)!=0) { - const char *ptr= (sym->documentation!=NULL) ? sym->documentation : ""; - error(234,sym->name,ptr); /* deprecated (probably a native function) */ - } /* if */ - - /* run through the arguments */ - arg=sym->dim.arglist; - assert(arg!=NULL); - stgmark(sSTARTREORDER); - memset(arglist,ARG_UNHANDLED,sizeof arglist); - if (matchparanthesis) { - /* Opening brace was already parsed, if closing brace follows, this - * call passes no parameters. - */ - close=matchtoken(')'); - } else { - /* When we find an end of line here, it may be a function call passing - * no parameters, or it may be that the first parameter is on a line - * below. But as a parameter can be anything, this is difficult to check. - * The only simple check that we have is the use of "named parameters". - */ - close=matchtoken(tTERM); - if (close) { - close=!matchtoken('.'); - if (!close) - lexpush(); /* reset the '.' */ - } /* if */ - } /* if */ - if (pending_this || !close) { - do { - if (!pending_this && matchtoken('.')) { - namedparams=TRUE; - if (!needtoken(tSYMBOL)) - break; - tokeninfo(&lexval,&lexstr); - argpos=findnamedarg(arg,lexstr); - if (argpos<0) { - error(17,lexstr); /* undefined symbol */ - break; /* exit loop, argpos is invalid */ - } /* if */ - needtoken('='); - argidx=argpos; - } else { - if (namedparams) - error(44); /* positional parameters must precede named parameters */ - argpos=nargs; - } /* if */ - /* the number of arguments this was already checked at the declaration - * of the function; check it again for functions with a variable - * argument list - */ - if (argpos>=sMAXARGS) - error(45); /* too many function arguments */ - stgmark((char)(sEXPRSTART+argpos));/* mark beginning of new expression in stage */ - if (arglist[argpos]!=ARG_UNHANDLED) - error(58); /* argument already set */ - if (!pending_this && matchtoken('_')) { - arglist[argpos]=ARG_IGNORED; /* flag argument as "present, but ignored" */ - if (arg[argidx].ident==0 || arg[argidx].ident==iVARARGS) { - error(92); /* argument count mismatch */ - } else if (!arg[argidx].hasdefault) { - error(34,nargs+1); /* argument has no default value */ - } /* if */ - if (arg[argidx].ident!=0 && arg[argidx].ident!=iVARARGS) - argidx++; - /* The rest of the code to handle default values is at the bottom - * of this routine where default values for unspecified parameters - * are (also) handled. Note that above, the argument is flagged as - * ARG_IGNORED. - */ - } else { - arglist[argpos]=ARG_DONE; /* flag argument as "present" */ - if (arg[argidx].ident!=0 && arg[argidx].numtags==1) /* set the expected tag, if any */ - lval.cmptag=arg[argidx].tags[0]; - if (pending_this) { - lval = implicitthis->val; - lvalue = implicitthis->lvalue; - } else { - lvalue = hier14(&lval); - if (lvalue && lval.ident == iACCESSOR) { - rvalue(&lval); - lvalue = FALSE; - } - } - assert(sc_status==statFIRST || arg[argidx].ident == 0 || arg[argidx].tags!=NULL); - switch (arg[argidx].ident) { - case 0: - /* On the first pass, we donm't have all of the parameter info. - * Hpwever, use information must be marked anyway, otherwise vars - * declared previously will be omitted in the second psas. See - * SourceMod bug 4643. - */ - error(92); /* argument count mismatch */ - if (lval.sym) - markusage(lval.sym, uREAD); - break; - case iVARARGS: - /* always pass by reference */ - if (lval.ident==iVARIABLE || lval.ident==iREFERENCE) { - assert(lval.sym!=NULL); - if ((lval.sym->usage & uCONST)!=0 && (arg[argidx].usage & uCONST)==0) { - /* treat a "const" variable passed to a function with a non-const - * "variable argument list" as a constant here */ - if (!lvalue) { - error(22); /* need lvalue */ - } else { - rvalue(&lval); /* get value in PRI */ - setheap_pri(); /* address of the value on the heap in PRI */ - heapalloc+=markheap(MEMUSE_STATIC, 1); - nest_stkusage++; - } /* if */ - } else if (lvalue) { - address(lval.sym,sPRI); - } else { - setheap_pri(); /* address of the value on the heap in PRI */ - heapalloc+=markheap(MEMUSE_STATIC, 1); - nest_stkusage++; - } /* if */ - } else if (lval.ident==iCONSTEXPR || lval.ident==iEXPRESSION) - { - /* allocate a cell on the heap and store the - * value (already in PRI) there */ - setheap_pri(); /* address of the value on the heap in PRI */ - heapalloc+=markheap(MEMUSE_STATIC, 1); - nest_stkusage++; - } /* if */ - /* ??? handle const array passed by reference */ - /* otherwise, the address is already in PRI */ - if (lval.sym!=NULL) - markusage(lval.sym,uWRITTEN); - if (!checktags_string(arg[argidx].tags, arg[argidx].numtags, &lval) - && !checktag(arg[argidx].tags,arg[argidx].numtags,lval.tag)) - error(213); - break; - case iVARIABLE: - if (lval.ident==iLABEL || lval.ident==iFUNCTN || lval.ident==iREFFUNC - || lval.ident==iARRAY || lval.ident==iREFARRAY) - error(35,argidx+1); /* argument type mismatch */ - if (lvalue) - rvalue(&lval); /* get value (direct or indirect) */ - /* otherwise, the expression result is already in PRI */ - assert(arg[argidx].numtags>0); - check_userop(NULL,lval.tag,arg[argidx].tags[0],2,NULL,&lval.tag); - if (!checktags_string(arg[argidx].tags, arg[argidx].numtags, &lval)) - checktag(arg[argidx].tags, arg[argidx].numtags, lval.tag); - if (lval.tag!=0) - append_constval(&taglst,arg[argidx].name,lval.tag,0); - argidx++; /* argument done */ - break; - case iREFERENCE: - if (!lvalue) - error(35,argidx+1); /* argument type mismatch */ - if (lval.sym!=NULL && (lval.sym->usage & uCONST)!=0 && (arg[argidx].usage & uCONST)==0) - error(35,argidx+1); /* argument type mismatch */ - if (lval.ident==iVARIABLE || lval.ident==iREFERENCE) { - if (lvalue) { - assert(lval.sym!=NULL); - address(lval.sym,sPRI); - } else { - setheap_pri(); /* address of the value on the heap in PRI */ - heapalloc+=markheap(MEMUSE_STATIC, 1); - nest_stkusage++; - } /* if */ - } /* if */ - /* otherwise, the address is already in PRI */ - checktag(arg[argidx].tags,arg[argidx].numtags,lval.tag); - if (lval.tag!=0) - append_constval(&taglst,arg[argidx].name,lval.tag,0); - argidx++; /* argument done */ - if (lval.sym!=NULL) - markusage(lval.sym,uWRITTEN); - break; - case iREFARRAY: - if (lval.ident!=iARRAY && lval.ident!=iREFARRAY - && lval.ident!=iARRAYCELL && lval.ident!=iARRAYCHAR) - { - error(35,argidx+1); /* argument type mismatch */ - break; - } /* if */ - if (lval.sym!=NULL && (lval.sym->usage & uCONST)!=0 && (arg[argidx].usage & uCONST)==0) - error(35,argidx+1); /* argument type mismatch */ - /* Verify that the dimensions match with those in arg[argidx]. - * A literal array always has a single dimension. - * An iARRAYCELL parameter is also assumed to have a single dimension. - */ - if (lval.sym==NULL || lval.ident==iARRAYCELL || lval.ident==iARRAYCHAR) { - if (arg[argidx].numdim!=1) { - error(48); /* array dimensions must match */ - } else if (arg[argidx].dim[0]!=0) { - assert(arg[argidx].dim[0]>0); - if (lval.ident==iARRAYCELL) { - error(47); /* array sizes must match */ - } else { - assert(lval.constval!=0); /* literal array must have a size */ - /* A literal array must have exactly the same size as the - * function argument; a literal string may be smaller than - * the function argument. - */ - if ((lval.constval>0 && arg[argidx].dim[0]!=lval.constval) - || (lval.constval<0 && arg[argidx].dim[0] < -lval.constval)) - error(47); /* array sizes must match */ - } /* if */ - } /* if */ - if (lval.ident!=iARRAYCELL && lval.ident!=iARRAYCHAR) { - /* save array size, for default values with uSIZEOF flag */ - cell array_sz=lval.constval; - assert(array_sz!=0);/* literal array must have a size */ - if (array_sz<0) - array_sz= -array_sz; - append_constval(&arrayszlst,arg[argidx].name,array_sz,0); - }/* if */ - } else { - symbol *sym=lval.sym; - short level=0; - assert(sym!=NULL); - if (sym->dim.array.level+1!=arg[argidx].numdim) - error(48); /* array dimensions must match */ - /* the lengths for all dimensions must match, unless the dimension - * length was defined at zero (which means "undefined") - */ - while (sym->dim.array.level>0) { - assert(leveldim.array.length!=arg[argidx].dim[level]) - error(47); /* array sizes must match */ - else if (!matchtag(arg[argidx].idxtag[level],sym->x.tags.index,TRUE)) - error(229,sym->name); /* index tag mismatch */ - append_constval(&arrayszlst,arg[argidx].name,sym->dim.array.length,level); - sym=finddepend(sym); - assert(sym!=NULL); - level++; - } /* if */ - /* the last dimension is checked too, again, unless it is zero */ - assert(leveldim.array.length!=arg[argidx].dim[level]) - error(47); /* array sizes must match */ - else if (!matchtag(arg[argidx].idxtag[level],sym->x.tags.index,TRUE)) - error(229,sym->name); /* index tag mismatch */ - append_constval(&arrayszlst,arg[argidx].name,sym->dim.array.length,level); - } /* if */ - /* address already in PRI */ - - checktag(arg[argidx].tags,arg[argidx].numtags,lval.tag); - - if (arg[argidx].numtags > 0) { - if ((arg[argidx].tags[0] != pc_tag_string && lval.tag == pc_tag_string) || - (arg[argidx].tags[0] == pc_tag_string && lval.tag != pc_tag_string)) - { - error(178, type_to_name(lval.tag), type_to_name(arg[argidx].tags[0])); - } - } - - if (lval.tag!=0) - append_constval(&taglst,arg[argidx].name,lval.tag,0); - // ??? set uWRITTEN? - argidx++; /* argument done */ - break; - } /* switch */ - pushreg(sPRI); /* store the function argument on the stack */ - markexpr(sPARM,NULL,0); /* mark the end of a sub-expression */ - nest_stkusage++; - } /* if */ - assert(arglist[argpos]!=ARG_UNHANDLED); - nargs++; - - /** - * We can already have decided it was time to close because of pending_this. - * If that's the case, then bail out now. - */ - if (pending_this && close) { - pending_this = FALSE; - break; - } - - if (matchparanthesis) { - close=matchtoken(')'); - if (!close) /* if not paranthese... */ - /* Not expecting comma if the first argument was implicit. */ - if (!pending_this && !needtoken(',')) - break; /* ...but abort loop if neither */ - } else { - /* Not expecting comma if the first argument was implicit. */ - close = (!pending_this && !matchtoken(',')); - if (close) { /* if not comma... */ - if (needtoken(tTERM)==1)/* ...must be end of statement */ - lexpush(); /* push again, because end of statement is analised later */ - } /* if */ - } /* if */ - - pending_this = FALSE; - } while (!close && freading && !matchtoken(tENDEXPR)); /* do */ - } /* if */ - /* check remaining function arguments (they may have default values) */ - for (argidx=0; arg[argidx].ident!=0 && arg[argidx].ident!=iVARARGS; argidx++) { - if (arglist[argidx]==ARG_DONE) - continue; /* already seen and handled this argument */ - stgmark((char)(sEXPRSTART+argidx));/* mark beginning of new expression in stage */ - if (arg[argidx].hasdefault) { - if (arg[argidx].ident==iREFARRAY) { - short level; - setdefarray(arg[argidx].defvalue.array.data, - arg[argidx].defvalue.array.size, - arg[argidx].defvalue.array.arraysize, - &arg[argidx].defvalue.array.addr, - (arg[argidx].usage & uCONST)!=0); - if (arg[argidx].defvalue.array.data != NULL) { - if ((arg[argidx].usage & uCONST)==0) { - heapalloc+=arg[argidx].defvalue.array.arraysize; - nest_stkusage+=arg[argidx].defvalue.array.arraysize; - } /* if */ - /* keep the lengths of all dimensions of a multi-dimensional default array */ - assert(arg[argidx].numdim>0); - if (arg[argidx].numdim==1) { - append_constval(&arrayszlst,arg[argidx].name,arg[argidx].defvalue.array.arraysize,0); - } else { - for (level=0; level0); - check_userop(NULL,arg[argidx].defvalue_tag,arg[argidx].tags[0],2,NULL,&dummytag); - assert(dummytag==arg[argidx].tags[0]); - } /* if */ - pushreg(sPRI); /* store the function argument on the stack */ - markexpr(sPARM,NULL,0); /* mark the end of a sub-expression */ - nest_stkusage++; - } else { - error(92,argidx); /* argument count mismatch */ - } /* if */ - if (arglist[argidx]==ARG_UNHANDLED) - nargs++; - arglist[argidx]=ARG_DONE; - } /* for */ - stgmark(sENDREORDER); /* mark end of reversed evaluation */ - pushval((cell)nargs /* *sizeof(cell)*/ ); - nest_stkusage++; - ffcall(sym,NULL,nargs); - if (sc_status!=statSKIP) - markusage(sym,uREAD); /* do not mark as "used" when this call itself is skipped */ - if ((sym->usage & uNATIVE)!=0 &&sym->x.lib!=NULL) - sym->x.lib->value += 1; /* increment "usage count" of the library */ - if (symret!=NULL) - popreg(sPRI); /* pop hidden parameter as function result */ - sideeffect=TRUE; /* assume functions carry out a side-effect */ - delete_consttable(&arrayszlst); /* clear list of array sizes */ - delete_consttable(&taglst); /* clear list of parameter tags */ - - /* maintain max. amount of memory used */ - { - long totalsize; - totalsize=declared+heapalloc+1; /* local variables & return value size, - * +1 for PROC opcode */ - if (lval_result->ident==iREFARRAY) - totalsize++; /* add hidden parameter (on the stack) */ - if ((sym->usage & uNATIVE)==0) - totalsize++; /* add "call" opcode */ - totalsize+=nest_stkusage; - if (curfunc != NULL) { - if (curfunc->x.stacksizex.stacksize=totalsize; - } else { - error(10); - } - nest_stkusage-=nargs+heapalloc+1; /* stack/heap space, +1 for argcount param */ - /* if there is a syntax error in the script, the stack calculation is - * probably incorrect; but we may not allow it to drop below zero - */ - if (nest_stkusage<0) - nest_stkusage=0; - } - - /* scrap any arrays left on the heap, with the exception of the array that - * this function has as a result (in other words, scrap all arrays on the - * heap that caused by expressions in the function arguments) - */ - popheaplist(); - nesting--; -} - -/* dbltest - * - * Returns a non-zero value if lval1 an array and lval2 is not an array and - * the operation is addition or subtraction. - * - * Returns the "shift" count (1 for 16-bit, 2 for 32-bit) to align a cell - * to an array offset. - */ -static int dbltest(void (*oper)(),value *lval1,value *lval2) -{ - if ((oper!=ob_add) && (oper!=ob_sub)) - return 0; - if (lval1->ident!=iARRAY) - return 0; - if (lval2->ident==iARRAY) - return 0; - return sizeof(cell)/2; /* 1 for 16-bit, 2 for 32-bit */ -} - -/* commutative - * - * Test whether an operator is commutative, i.e. x oper y == y oper x. - * Commutative operators are: + (addition) - * * (multiplication) - * == (equality) - * != (inequality) - * & (bitwise and) - * ^ (bitwise xor) - * | (bitwise or) - * - * If in an expression, code for the left operand has been generated and - * the right operand is a constant and the operator is commutative, the - * precautionary "push" of the primary register is scrapped and the constant - * is read into the secondary register immediately. - */ -static int commutative(void (*oper)()) -{ - return oper==ob_add || oper==os_mult - || oper==ob_eq || oper==ob_ne - || oper==ob_and || oper==ob_xor || oper==ob_or; -} - -/* constant - * - * Generates code to fetch a number, a literal character (which is returned - * by lex() as a number as well) or a literal string (lex() stores the - * strings in the literal queue). If the operand was a number, it is stored - * in lval->constval. - * - * The function returns 1 if the token was a constant or a string, 0 - * otherwise. - */ -static int constant(value *lval) -{ - int tok,index,ident; - cell val,item,cidx; - char *st; - symbol *sym; - int cmptag=lval->cmptag; - - tok=lex(&val,&st); - if (tok==tSYMBOL && (sym=findconst(st,&cmptag))!=0) { - if (cmptag>1) - error(91,sym->name); /* ambiguity: multiple matching constants (different tags) */ - lval->constval=sym->addr; - ldconst(lval->constval,sPRI); - lval->ident=iCONSTEXPR; - lval->tag=sym->tag; - lval->sym=sym; - markusage(sym,uREAD); - } else if (tok==tNULL) { - lval->constval = 0; - ldconst(lval->constval, sPRI); - lval->ident = iCONSTEXPR; - lval->tag = pc_tag_null_t; - } else if (tok==tNUMBER) { - lval->constval=val; - ldconst(lval->constval,sPRI); - lval->ident=iCONSTEXPR; - } else if (tok==tRATIONAL) { - lval->constval=val; - ldconst(lval->constval,sPRI); - lval->ident=iCONSTEXPR; - lval->tag=sc_rationaltag; - } else if (tok==tSTRING) { - /* lex() stores starting index of string in the literal table in 'val' */ - ldconst((val+glb_declared)*sizeof(cell),sPRI); - lval->ident=iARRAY; /* pretend this is a global array */ - lval->constval=val-litidx; /* constval == the negative value of the - * size of the literal array; using a negative - * value distinguishes between literal arrays - * and literal strings (this was done for - * array assignment). */ - lval->tag=pc_tag_string; - } else if (tok=='{') { - int tag,lasttag=-1; - val=litidx; - do { - /* cannot call constexpr() here, because "staging" is already turned - * on at this point */ - assert(staging); - stgget(&index,&cidx); /* mark position in code generator */ - ident=expression(&item,&tag,NULL,FALSE,NULL); - stgdel(index,cidx); /* scratch generated code */ - if (ident!=iCONSTEXPR) - error(8); /* must be constant expression */ - if (lasttag<0) - lasttag=tag; - else - matchtag(lasttag,tag,FALSE); - litadd(item); /* store expression result in literal table */ - } while (matchtoken(',')); - if (!needtoken('}')) - lexclr(FALSE); - ldconst((val+glb_declared)*sizeof(cell),sPRI); - lval->ident=iARRAY; /* pretend this is a global array */ - lval->constval=litidx-val; /* constval == the size of the literal array */ - } else { - return FALSE; /* no, it cannot be interpreted as a constant */ - } /* if */ - return TRUE; /* yes, it was a constant value */ -} - diff --git a/sourcepawn/compiler/sc4.cpp b/sourcepawn/compiler/sc4.cpp deleted file mode 100644 index 3cee7511..00000000 --- a/sourcepawn/compiler/sc4.cpp +++ /dev/null @@ -1,1519 +0,0 @@ -// vim: set ts=8 sts=2 sw=2 tw=99 et: -/* Pawn compiler - code generation (unoptimized "assembler" code) - * - * Copyright (c) ITB CompuPhase, 1997-2006 - * - * This software is provided "as-is", without any express or implied warranty. - * In no event will the authors be held liable for any damages arising from - * the use of this software. - * - * Permission is granted to anyone to use this software for any purpose, - * including commercial applications, and to alter it and redistribute it - * freely, subject to the following restrictions: - * - * 1. The origin of this software must not be misrepresented; you must not - * claim that you wrote the original software. If you use this software in - * a product, an acknowledgment in the product documentation would be - * appreciated but is not required. - * 2. Altered source versions must be plainly marked as such, and must not be - * misrepresented as being the original software. - * 3. This notice may not be removed or altered from any source distribution. - * - * Version: $Id$ - */ -#include -#include -#include -#include /* for _MAX_PATH */ -#include -#if defined FORTIFY - #include -#endif -#include "sc.h" -#include "sctracker.h" - -static int fcurseg; /* the file number (fcurrent) for the active segment */ - -void load_i(); - -/* When a subroutine returns to address 0, the AMX must halt. In earlier - * releases, the RET and RETN opcodes checked for the special case 0 address. - * Today, the compiler simply generates a HALT instruction at address 0. So - * a subroutine can savely return to 0, and then encounter a HALT. - */ -void writeleader(symbol *root) -{ - int lbl_nostate,lbl_table; - int statecount; - symbol *sym; - constvalue *fsa, *state, *stlist; - int fsa_id,listid; - char lbl_default[sNAMEMAX+1]; - - assert(code_idx==0); - - begcseg(); - stgwrite(";program exit point\n"); - stgwrite("\thalt 0\n\n"); - code_idx+=opcodes(1)+opargs(1); /* calculate code length */ - - /* check whether there are any functions that have states */ - for (sym=root->next; sym!=NULL; sym=sym->next) - if (sym->ident==iFUNCTN && (sym->usage & (uPUBLIC | uREAD))!=0 && sym->states!=NULL) - break; - if (sym==NULL) - return; /* no function has states, nothing to do next */ - - /* generate an error function that is called for an undefined state */ - stgwrite("\n;exit point for functions called from the wrong state\n"); - lbl_nostate=getlabel(); - setlabel(lbl_nostate); - stgwrite("\thalt "); - outval(AMX_ERR_INVSTATE,TRUE); - code_idx+=opcodes(1)+opargs(1); /* calculate code length */ - - /* write the "state-selectors" table with all automatons (update the - * automatons structure too, as we are now assigning the address to - * each automaton state-selector variable) - */ - assert(glb_declared==0); - begdseg(); - for (fsa=sc_automaton_tab.next; fsa!=NULL; fsa=fsa->next) { - defstorage(); - stgwrite("0\t; automaton "); - if (strlen(fsa->name)==0) - stgwrite("(anonymous)"); - else - stgwrite(fsa->name); - stgwrite("\n"); - fsa->value=glb_declared*sizeof(cell); - glb_declared++; - } /* for */ - - /* write stubs and jump tables for all state functions */ - begcseg(); - for (sym=root->next; sym!=NULL; sym=sym->next) { - if (sym->ident==iFUNCTN && (sym->usage & (uPUBLIC | uREAD))!=0 && sym->states!=NULL) { - stlist=sym->states->next; - assert(stlist!=NULL); /* there should be at least one state item */ - listid=stlist->index; - assert(listid==-1 || listid>0); - if (listid==-1 && stlist->next!=NULL) { - /* first index is the "fallback", take the next one (if available) */ - stlist=stlist->next; - listid=stlist->index; - } /* if */ - if (listid==-1) { - /* first index is the fallback, there is no second... */ - strcpy(stlist->name,"0"); /* insert dummy label number */ - /* this is an error, but we postpone adding the error message until the - * function definition - */ - continue; - } /* if */ - /* generate label numbers for all statelist ids */ - for (stlist=sym->states->next; stlist!=NULL; stlist=stlist->next) { - assert(strlen(stlist->name)==0); - strcpy(stlist->name,itoh(getlabel())); - } /* for */ - if (strcmp(sym->name,uENTRYFUNC)==0) - continue; /* do not generate stubs for this special function */ - sym->addr=code_idx; /* fix the function address now */ - /* get automaton id for this function */ - assert(listid>0); - fsa_id=state_getfsa(listid); - assert(fsa_id>=0); /* automaton 0 exists */ - fsa=automaton_findid(fsa_id); - /* count the number of states actually used; at the sane time, check - * whether there is a default state function - */ - statecount=0; - strcpy(lbl_default,itoh(lbl_nostate)); - for (stlist=sym->states->next; stlist!=NULL; stlist=stlist->next) { - if (stlist->index==-1) { - assert(strlen(stlist->name)name); - } else { - statecount+=state_count(stlist->index); - } /* if */ - } /* for */ - /* generate a stub entry for the functions */ - stgwrite("\tload.pri "); - outval(fsa->value,FALSE); - stgwrite("\t; "); - stgwrite(sym->name); - stgwrite("\n"); - code_idx+=opcodes(1)+opargs(1); /* calculate code length */ - lbl_table=getlabel(); - ffswitch(lbl_table); - /* generate the jump table */ - setlabel(lbl_table); - ffcase(statecount,lbl_default,TRUE); - for (state=sc_state_tab.next; state!=NULL; state=state->next) { - if (state->index==fsa_id) { - /* find the label for this list id */ - for (stlist=sym->states->next; stlist!=NULL; stlist=stlist->next) { - if (stlist->index!=-1 && state_inlist(stlist->index,(int)state->value)) { - ffcase(state->value,stlist->name,FALSE); - break; - } /* if */ - } /* for */ - if (stlist==NULL && strtol(lbl_default,NULL,16)==lbl_nostate) - error(230,state->name,sym->name); /* unimplemented state, no fallback */ - } /* if (state belongs to automaton of function) */ - } /* for (state) */ - stgwrite("\n"); - } /* if (is function, used & having states) */ - } /* for (sym) */ -} - -/* writetrailer - * Not much left of this once important function. - * - * Global references: pc_stksize (referred to only) - * sc_dataalign (referred to only) - * code_idx (altered) - * glb_declared (altered) - */ -void writetrailer(void) -{ - assert(sc_dataalign % opcodes(1) == 0); /* alignment must be a multiple of - * the opcode size */ - assert(sc_dataalign!=0); - - /* pad code to align data segment */ - if ((code_idx % sc_dataalign)!=0) { - begcseg(); - while ((code_idx % sc_dataalign)!=0) - nooperation(); - } /* if */ - - /* pad data segment to align the stack and the heap */ - assert(litidx==0); /* literal queue should have been emptied */ - assert(sc_dataalign % sizeof(cell) == 0); - if (((glb_declared*sizeof(cell)) % sc_dataalign)!=0) { - begdseg(); - defstorage(); - while (((glb_declared*sizeof(cell)) % sc_dataalign)!=0) { - stgwrite("0 "); - glb_declared++; - } /* while */ - } /* if */ - - stgwrite("\nSTKSIZE "); /* write stack size (align stack top) */ - outval(pc_stksize - (pc_stksize % sc_dataalign), TRUE); -} - -/* - * Start (or restart) the CODE segment. - * - * In fact, the code and data segment specifiers are purely informational; - * the "DUMP" instruction itself already specifies that the following values - * should go to the data segment. All other instructions go to the code - * segment. - * - * Global references: curseg - * fcurrent - */ -void begcseg(void) -{ - if (sc_status!=statSKIP && (curseg!=sIN_CSEG || fcurrent!=fcurseg)) { - stgwrite("\n"); - stgwrite("CODE "); - outval(fcurrent,FALSE); - stgwrite("\t; "); - outval(code_idx,TRUE); - curseg=sIN_CSEG; - fcurseg=fcurrent; - } /* endif */ -} - -/* - * Start (or restart) the DATA segment. - * - * Global references: curseg - */ -void begdseg(void) -{ - if (sc_status!=statSKIP && (curseg!=sIN_DSEG || fcurrent!=fcurseg)) { - stgwrite("\n"); - stgwrite("DATA "); - outval(fcurrent,FALSE); - stgwrite("\t; "); - outval((glb_declared-litidx)*sizeof(cell),TRUE); - curseg=sIN_DSEG; - fcurseg=fcurrent; - } /* if */ -} - -void setline(int chkbounds) -{ - if (sc_asmfile) { - stgwrite("\t; line "); - outval(fline,TRUE); - } /* if */ - if ((sc_debug & sSYMBOLIC)!=0 || (chkbounds && (sc_debug & sCHKBOUNDS)!=0)) { - /* generate a "break" (start statement) opcode rather than a "line" opcode - * because earlier versions of Small/Pawn have an incompatible version of the - * line opcode - */ - stgwrite("\tbreak\t; "); - outval(code_idx,TRUE); - code_idx+=opcodes(1); - } /* if */ -} - -void setfiledirect(char *name) -{ - if (sc_status==statFIRST && sc_listing) { - assert(name!=NULL); - pc_writeasm(outf,"#file "); - pc_writeasm(outf,name); - pc_writeasm(outf,"\n"); - } /* if */ -} - -void setlinedirect(int line) -{ - if (sc_status==statFIRST && sc_listing) { - char string[40]; - sprintf(string,"#line %d\n",line); - pc_writeasm(outf,string); - } /* if */ -} - -/* setlabel - * - * Post a code label (specified as a number), on a new line. - */ -void setlabel(int number) -{ - assert(number>=0); - stgwrite("l."); - stgwrite((char *)itoh(number)); - /* To assist verification of the assembled code, put the address of the - * label as a comment. However, labels that occur inside an expression - * may move (through optimization or through re-ordering). So write the - * address only if it is known to accurate. - */ - if (!staging) { - stgwrite("\t\t; "); - outval(code_idx,FALSE); - } /* if */ - stgwrite("\n"); -} - -/* Write a token that signifies the start or end of an expression or special - * statement. This allows several simple optimizations by the peephole - * optimizer. - */ -void markexpr(optmark type,const char *name,cell offset) -{ - switch (type) { - case sEXPR: - stgwrite("\t;$exp\n"); - break; - case sPARM: - stgwrite("\t;$par\n"); - break; - case sLDECL: - assert(name!=NULL); - stgwrite("\t;$lcl "); - stgwrite(name); - stgwrite(" "); - outval(offset,TRUE); - break; - default: - assert(0); - } /* switch */ -} - -/* startfunc - declare a CODE entry point (function start) - * - * Global references: funcstatus (referred to only) - */ -void startfunc(char *fname) -{ - stgwrite("\tproc"); - if (sc_asmfile) { - char symname[2*sNAMEMAX+16]; - funcdisplayname(symname,fname); - stgwrite("\t; "); - stgwrite(symname); - } /* if */ - stgwrite("\n"); - code_idx+=opcodes(1); -} - -/* endfunc - * - * Declare a CODE ending point (function end) - */ -void endfunc(void) -{ - stgwrite("\n"); /* skip a line */ -} - -/* alignframe - * - * Aligns the frame (and the stack) of the current function to a multiple - * of the specified byte count. Two caveats: the alignment ("numbytes") should - * be a power of 2, and this alignment must be done right after the frame - * is set up (before the first variable is declared) - */ -void alignframe(int numbytes) -{ - #if !defined NDEBUG - /* "numbytes" should be a power of 2 for this code to work */ - size_t i; - int count=0; - for (i=0; isym; - if (lval->ident==iARRAYCELL) { - /* indirect fetch, address already in PRI */ - load_i(); - } else if (lval->ident==iARRAYCHAR) { - /* indirect fetch of a character from a pack, address already in PRI */ - stgwrite("\tlodb.i "); - outval(sCHARBITS/8,TRUE); /* read one or two bytes */ - code_idx+=opcodes(1)+opargs(1); - } else if (lval->ident==iREFERENCE) { - /* indirect fetch, but address not yet in PRI */ - assert(sym!=NULL); - assert(sym->vclass==sLOCAL);/* global references don't exist in Pawn */ - if (sym->vclass==sLOCAL) - stgwrite("\tlref.s.pri "); - else - stgwrite("\tlref.pri "); - outval(sym->addr,TRUE); - markusage(sym,uREAD); - code_idx+=opcodes(1)+opargs(1); - } else if (lval->ident==iACCESSOR) { - invoke_getter(lval->accessor); - lval->ident=iEXPRESSION; - lval->accessor=NULL; - } else { - /* direct or stack relative fetch */ - assert(sym!=NULL); - if (sym->vclass==sLOCAL) - stgwrite("\tload.s.pri "); - else - stgwrite("\tload.pri "); - outval(sym->addr,TRUE); - markusage(sym,uREAD); - code_idx+=opcodes(1)+opargs(1); - } /* if */ -} - -/* Get the address of a symbol into the primary or alternate register (used - * for arrays, and for passing arguments by reference). - */ -void address(symbol *sym,regid reg) -{ - assert(sym!=NULL); - assert(reg==sPRI || reg==sALT); - /* the symbol can be a local array, a global array, or an array - * that is passed by reference. - */ - if (sym->ident==iREFARRAY || sym->ident==iREFERENCE) { - /* reference to a variable or to an array; currently this is - * always a local variable */ - switch (reg) { - case sPRI: - stgwrite("\tload.s.pri "); - break; - case sALT: - stgwrite("\tload.s.alt "); - break; - } /* switch */ - } else { - /* a local array or local variable */ - switch (reg) { - case sPRI: - if (sym->vclass==sLOCAL) - stgwrite("\taddr.pri "); - else - stgwrite("\tconst.pri "); - break; - case sALT: - if (sym->vclass==sLOCAL) - stgwrite("\taddr.alt "); - else - stgwrite("\tconst.alt "); - break; - } /* switch */ - } /* if */ - outval(sym->addr,TRUE); - markusage(sym,uREAD); - code_idx+=opcodes(1)+opargs(1); -} - -static void addr_reg(int val, regid reg) -{ - if (reg == sPRI) - stgwrite("\taddr.pri "); - else - stgwrite("\taddr.alt "); - outval(val, TRUE); - code_idx += opcodes(1) + opargs(1); -} - -// Load the number of arguments into PRI. Frame layout: -// base + 0*sizeof(cell) == previous "base" -// base + 1*sizeof(cell) == function return address -// base + 2*sizeof(cell) == number of arguments -// base + 3*sizeof(cell) == first argument of the function -static void load_argcount(regid reg) -{ - if (reg == sPRI) - stgwrite("\tload.s.pri "); - else - stgwrite("\tload.s.alt "); - outval(2 * sizeof(cell), TRUE); - code_idx += opcodes(1) + opargs(1); -} - -// PRI = ALT + (PRI * cellsize) -void idxaddr() -{ - stgwrite("\tidxaddr\n"); - code_idx += opcodes(1); -} - -void load_i() -{ - stgwrite("\tload.i\n"); - code_idx+=opcodes(1); -} - -// Load the hidden array argument into ALT. -void load_hidden_arg() -{ - pushreg(sPRI); - - // Compute an address to the first argument, then add the argument count - // to find the address after the final argument: - // addr.alt 0xc ; Compute &first_arg - // load.s.alt 0x8 ; Load arg count - // idxaddr ; Compute (&first_arg) + argcount - // load.i ; Load *(&first_arg + argcount) - // move.alt ; Move result into ALT. - addr_reg(0xc, sALT); - load_argcount(sPRI); - idxaddr(); - load_i(); - move_alt(); - - popreg(sPRI); -} - -/* store - * - * Saves the contents of "primary" into a memory cell, either directly - * or indirectly (at the address given in the alternate register). - */ -void store(value *lval) -{ - symbol *sym; - - sym=lval->sym; - if (lval->ident==iARRAYCELL) { - /* store at address in ALT */ - stgwrite("\tstor.i\n"); - code_idx+=opcodes(1); - } else if (lval->ident==iARRAYCHAR) { - /* store at address in ALT */ - stgwrite("\tstrb.i "); - outval(sCHARBITS/8,TRUE); /* write one or two bytes */ - code_idx+=opcodes(1)+opargs(1); - } else if (lval->ident==iREFERENCE) { - assert(sym!=NULL); - if (sym->vclass==sLOCAL) - stgwrite("\tsref.s.pri "); - else - stgwrite("\tsref.pri "); - outval(sym->addr,TRUE); - code_idx+=opcodes(1)+opargs(1); - } else if (lval->ident==iACCESSOR) { - invoke_setter(lval->accessor, TRUE); - } else { - assert(sym!=NULL); - markusage(sym,uWRITTEN); - if (sym->vclass==sLOCAL) - stgwrite("\tstor.s.pri "); - else - stgwrite("\tstor.pri "); - outval(sym->addr,TRUE); - code_idx+=opcodes(1)+opargs(1); - } /* if */ -} - -/* Get a cell from a fixed address in memory */ -void loadreg(cell address,regid reg) -{ - assert(reg==sPRI || reg==sALT); - if (reg==sPRI) - stgwrite("\tload.pri "); - else - stgwrite("\tload.alt "); - outval(address,TRUE); - code_idx+=opcodes(1)+opargs(1); -} - -/* Store a cell into a fixed address in memory */ -void storereg(cell address,regid reg) -{ - assert(reg==sPRI || reg==sALT); - if (reg==sPRI) - stgwrite("\tstor.pri "); - else - stgwrite("\tstor.alt "); - outval(address,TRUE); - code_idx+=opcodes(1)+opargs(1); -} - -/* source must in PRI, destination address in ALT. The "size" - * parameter is in bytes, not cells. - */ -void memcopy(cell size) -{ - stgwrite("\tmovs "); - outval(size,TRUE); - - code_idx+=opcodes(1)+opargs(1); -} - -/* Address of the source must already have been loaded in PRI - * "size" is the size in bytes (not cells). - */ -void copyarray(symbol *sym,cell size) -{ - assert(sym!=NULL); - /* the symbol can be a local array, a global array, or an array - * that is passed by reference. - */ - if (sym->ident==iREFARRAY) { - /* reference to an array; currently this is always a local variable */ - assert(sym->vclass==sLOCAL); /* symbol must be stack relative */ - stgwrite("\tload.s.alt "); - } else { - /* a local or global array */ - if (sym->vclass==sLOCAL) - stgwrite("\taddr.alt "); - else - stgwrite("\tconst.alt "); - } /* if */ - outval(sym->addr,TRUE); - markusage(sym,uWRITTEN); - - code_idx+=opcodes(1)+opargs(1); - memcopy(size); -} - -void fillarray(symbol *sym,cell size,cell value) -{ - ldconst(value,sPRI); /* load value in PRI */ - - assert(sym!=NULL); - /* the symbol can be a local array, a global array, or an array - * that is passed by reference. - */ - if (sym->ident==iREFARRAY) { - /* reference to an array; currently this is always a local variable */ - assert(sym->vclass==sLOCAL); /* symbol must be stack relative */ - stgwrite("\tload.s.alt "); - } else { - /* a local or global array */ - if (sym->vclass==sLOCAL) - stgwrite("\taddr.alt "); - else - stgwrite("\tconst.alt "); - } /* if */ - outval(sym->addr,TRUE); - markusage(sym,uWRITTEN); - - assert(size>0); - stgwrite("\tfill "); - outval(size,TRUE); - - code_idx+=opcodes(2)+opargs(2); -} - -void stradjust(regid reg) -{ - assert(reg==sPRI); - stgwrite("\tstradjust.pri\n"); - code_idx+=opcodes(1); -} - -/* Instruction to get an immediate value into the primary or the alternate - * register - */ -void ldconst(cell val,regid reg) -{ - assert(reg==sPRI || reg==sALT); - switch (reg) { - case sPRI: - if (val==0) { - stgwrite("\tzero.pri\n"); - code_idx+=opcodes(1); - } else { - stgwrite("\tconst.pri "); - outval(val, TRUE); - code_idx+=opcodes(1)+opargs(1); - } /* if */ - break; - case sALT: - if (val==0) { - stgwrite("\tzero.alt\n"); - code_idx+=opcodes(1); - } else { - stgwrite("\tconst.alt "); - outval(val, TRUE); - code_idx+=opcodes(1)+opargs(1); - } /* if */ - break; - } /* switch */ -} - -/* Copy value in alternate register to the primary register */ -void moveto1(void) -{ - stgwrite("\tmove.pri\n"); - code_idx+=opcodes(1)+opargs(0); -} - -void move_alt(void) -{ - stgwrite("\tmove.alt\n"); - code_idx+=opcodes(1)+opargs(0); -} - -/* Push primary or the alternate register onto the stack - */ -void pushreg(regid reg) -{ - assert(reg==sPRI || reg==sALT); - switch (reg) { - case sPRI: - stgwrite("\tpush.pri\n"); - break; - case sALT: - stgwrite("\tpush.alt\n"); - break; - } /* switch */ - code_idx+=opcodes(1); -} - -/* - * Push a constant value onto the stack - */ -void pushval(cell val) -{ - stgwrite("\tpush.c "); - outval(val, TRUE); - code_idx+=opcodes(1)+opargs(1); -} - -/* Pop stack into the primary or the alternate register - */ -void popreg(regid reg) -{ - assert(reg==sPRI || reg==sALT); - switch (reg) { - case sPRI: - stgwrite("\tpop.pri\n"); - break; - case sALT: - stgwrite("\tpop.alt\n"); - break; - } /* switch */ - code_idx+=opcodes(1); -} - -/* - * Generate an array - * stk -= dims - * [stk] = hea - * stk += 1 - * hea += 1 + (# cells in array) - */ -void genarray(int dims, int _autozero) -{ - if (_autozero) { - stgwrite("\tgenarray.z "); - } else { - stgwrite("\tgenarray "); - } - outval(dims, TRUE); - code_idx+=opcodes(1)+opargs(1); -} - -/* - * swap the top-of-stack with the value in primary register - */ -void swap1(void) -{ - stgwrite("\tswap.pri\n"); - code_idx+=opcodes(1); -} - -/* Switch statements - * The "switch" statement generates a "case" table using the "CASE" opcode. - * The case table contains a list of records, each record holds a comparison - * value and a label to branch to on a match. The very first record is an - * exception: it holds the size of the table (excluding the first record) and - * the label to branch to when none of the values in the case table match. - * The case table is sorted on the comparison value. This allows more advanced - * abstract machines to sift the case table with a binary search. - */ -void ffswitch(int label) -{ - stgwrite("\tswitch "); - outval(label,TRUE); /* the label is the address of the case table */ - code_idx+=opcodes(1)+opargs(1); -} - -void ffcase(cell value,char *labelname,int newtable) -{ - if (newtable) { - stgwrite("\tcasetbl\n"); - code_idx+=opcodes(1); - } /* if */ - stgwrite("\tcase "); - outval(value,FALSE); - stgwrite(" "); - stgwrite(labelname); - stgwrite("\n"); - code_idx+=opcodes(0)+opargs(2); -} - -/* - * Call specified function - */ -void ffcall(symbol *sym,const char *label,int numargs) -{ - char symname[2*sNAMEMAX+16]; - char aliasname[sNAMEMAX+1]; - int wasAlias = 0; - - assert(sym!=NULL); - assert(sym->ident==iFUNCTN); - if (sc_asmfile) - funcdisplayname(symname,sym->name); - if ((sym->usage & uNATIVE)!=0) { - /* reserve a SYSREQ id if called for the first time */ - assert(label==NULL); - stgwrite("\tsysreq.c "); - if (sc_status==statWRITE && (sym->usage & uREAD)==0 && sym->addr>=0) - sym->addr=ntv_funcid++; - /* Look for an alias */ - if (lookup_alias(aliasname, sym->name)) { - symbol *asym = findglb(aliasname, sGLOBAL); - if (asym && asym->ident==iFUNCTN && ((sym->usage & uNATIVE) != 0)) { - sym = asym; - if (sc_status==statWRITE && (sym->usage & uREAD)==0 && sym->addr>=0) { - sym->addr=ntv_funcid++; - markusage(sym, uREAD); - } - } - } - outval(sym->addr,FALSE); - if (sc_asmfile) { - stgwrite("\t; "); - stgwrite(symname); - } /* if */ - stgwrite("\n"); /* write on a separate line, to mark a sequence point for the peephole optimizer */ - stgwrite("\tstack "); - outval((numargs+1)*sizeof(cell), TRUE); - code_idx+=opcodes(2)+opargs(2); - } else { - /* normal function */ - stgwrite("\tcall "); - if (label!=NULL) { - stgwrite("l."); - stgwrite(label); - } else { - stgwrite(sym->name); - } /* if */ - if (sc_asmfile - && (label!=NULL || (!isalpha(sym->name[0]) && sym->name[0]!='_' && sym->name[0]!=sc_ctrlchar))) - { - stgwrite("\t; "); - stgwrite(symname); - } /* if */ - stgwrite("\n"); - code_idx+=opcodes(1)+opargs(1); - } /* if */ -} - -/* Return from function - * - * Global references: funcstatus (referred to only) - */ -void ffret(int remparams) -{ - if (remparams) - stgwrite("\tretn\n"); - else - stgwrite("\tret\n"); - code_idx+=opcodes(1); -} - -void ffabort(int reason) -{ - stgwrite("\thalt "); - outval(reason,TRUE); - code_idx+=opcodes(1)+opargs(1); -} - -void ffbounds(cell size) -{ - if ((sc_debug & sCHKBOUNDS)!=0) { - stgwrite("\tbounds "); - outval(size,TRUE); - code_idx+=opcodes(1)+opargs(1); - } /* if */ -} - -/* - * Jump to local label number (the number is converted to a name) - */ -void jumplabel(int number) -{ - stgwrite("\tjump "); - outval(number,TRUE); - code_idx+=opcodes(1)+opargs(1); -} - -/* - * Define storage (global and static variables) - */ -void defstorage(void) -{ - stgwrite("dump "); -} - -/* - * Inclrement/decrement stack pointer. Note that this routine does - * nothing if the delta is zero. - */ -void modstk(int delta) -{ - if (delta) { - stgwrite("\tstack "); - outval(delta, TRUE); - code_idx+=opcodes(1)+opargs(1); - } /* if */ -} - -/* set the stack to a hard offset from the frame */ -void setstk(cell value) -{ - stgwrite("\tstackadjust "); - assert(value<=0); /* STK should always become <= FRM */ - outval(value, TRUE); /* add (negative) offset */ - code_idx+=opcodes(1)+opargs(1); -} - -void modheap(int delta) -{ - if (delta) { - stgwrite("\theap "); - outval(delta, TRUE); - code_idx+=opcodes(1)+opargs(1); - } /* if */ -} - -void modheap_i() -{ - stgwrite("\ttracker.pop.setheap\n"); - code_idx+=opcodes(1); -} - -void setheap_save(cell value) -{ - assert(value); - stgwrite("\ttracker.push.c "); - outval(value, TRUE); - code_idx+=opcodes(1)+opargs(1); -} - -void setheap_pri(void) -{ - stgwrite("\theap "); /* ALT = HEA++ */ - outval(sizeof(cell), TRUE); - stgwrite("\tstor.i\n"); /* store PRI (default value) at address ALT */ - stgwrite("\tmove.pri\n"); /* move ALT to PRI: PRI contains the address */ - code_idx+=opcodes(3)+opargs(1); -} - -void setheap(cell value) -{ - stgwrite("\tconst.pri "); /* load default value in PRI */ - outval(value, TRUE); - code_idx+=opcodes(1)+opargs(1); - setheap_pri(); -} - -/* - * Convert a cell number to a "byte" address; i.e. double or quadruple - * the primary register. - */ -void cell2addr(void) -{ - #if PAWN_CELL_SIZE==16 - stgwrite("\tshl.c.pri 1\n"); - #elif PAWN_CELL_SIZE==32 - stgwrite("\tshl.c.pri 2\n"); - #elif PAWN_CELL_SIZE==64 - stgwrite("\tshl.c.pri 3\n"); - #else - #error Unsupported cell size - #endif - code_idx+=opcodes(1)+opargs(1); -} - -/* - * Double or quadruple the alternate register. - */ -void cell2addr_alt(void) -{ - #if PAWN_CELL_SIZE==16 - stgwrite("\tshl.c.alt 1\n"); - #elif PAWN_CELL_SIZE==32 - stgwrite("\tshl.c.alt 2\n"); - #elif PAWN_CELL_SIZE==64 - stgwrite("\tshl.c.alt 3\n"); - #else - #error Unsupported cell size - #endif - code_idx+=opcodes(1)+opargs(1); -} - -/* - * Convert "distance of addresses" to "number of cells" in between. - * Or convert a number of packed characters to the number of cells (with - * truncation). - */ -void addr2cell(void) -{ - #if PAWN_CELL_SIZE==16 - stgwrite("\tshr.c.pri 1\n"); - #elif PAWN_CELL_SIZE==32 - stgwrite("\tshr.c.pri 2\n"); - #elif PAWN_CELL_SIZE==64 - stgwrite("\tshr.c.pri 3\n"); - #else - #error Unsupported cell size - #endif - code_idx+=opcodes(1)+opargs(1); -} - -/* Convert from character index to byte address. This routine does - * nothing if a character has the size of a byte. - */ -void char2addr(void) -{ - #if sCHARBITS==16 - stgwrite("\tshl.c.pri 1\n"); - code_idx+=opcodes(1)+opargs(1); - #endif -} - -/* Align PRI (which should hold a character index) to an address. - * The first character in a "pack" occupies the highest bits of - * the cell. This is at the lower memory address on Big Endian - * computers and on the higher address on Little Endian computers. - * The ALIGN.pri/alt instructions must solve this machine dependence; - * that is, on Big Endian computers, ALIGN.pri/alt shuold do nothing - * and on Little Endian computers they should toggle the address. - * - * NOTE: For Source Pawn, this is fliped. It will do nothing on Little-Endian. - */ -void charalign(void) -{ -#if 0 /* TEMPORARILY DISABLED BECAUSE WE DON'T USE BIG ENDIAN */ - stgwrite("\talign.pri "); - outval(sCHARBITS/8,TRUE); - code_idx+=opcodes(1)+opargs(1); -#endif -} - -/* - * Add a constant to the primary register. - */ -void addconst(cell value) -{ - if (value!=0) { - stgwrite("\tadd.c "); - outval(value,TRUE); - code_idx+=opcodes(1)+opargs(1); - } /* if */ -} - -/* - * signed multiply of primary and secundairy registers (result in primary) - */ -void os_mult(void) -{ - stgwrite("\tsmul\n"); - code_idx+=opcodes(1); -} - -/* - * signed divide of alternate register by primary register (quotient in - * primary; remainder in alternate) - */ -void os_div(void) -{ - stgwrite("\tsdiv.alt\n"); - code_idx+=opcodes(1); -} - -/* - * modulus of (alternate % primary), result in primary (signed) - */ -void os_mod(void) -{ - stgwrite("\tsdiv.alt\n"); - stgwrite("\tmove.pri\n"); /* move ALT to PRI */ - code_idx+=opcodes(2); -} - -/* - * Add primary and alternate registers (result in primary). - */ -void ob_add(void) -{ - stgwrite("\tadd\n"); - code_idx+=opcodes(1); -} - -/* - * subtract primary register from alternate register (result in primary) - */ -void ob_sub(void) -{ - stgwrite("\tsub.alt\n"); - code_idx+=opcodes(1); -} - -/* - * arithmic shift left alternate register the number of bits - * given in the primary register (result in primary). - * There is no need for a "logical shift left" routine, since - * logical shift left is identical to arithmic shift left. - */ -void ob_sal(void) -{ - stgwrite("\txchg\n"); - stgwrite("\tshl\n"); - code_idx+=opcodes(2); -} - -/* - * arithmic shift right alternate register the number of bits - * given in the primary register (result in primary). - */ -void os_sar(void) -{ - stgwrite("\txchg\n"); - stgwrite("\tsshr\n"); - code_idx+=opcodes(2); -} - -/* - * logical (unsigned) shift right of the alternate register by the - * number of bits given in the primary register (result in primary). - */ -void ou_sar(void) -{ - stgwrite("\txchg\n"); - stgwrite("\tshr\n"); - code_idx+=opcodes(2); -} - -/* - * inclusive "or" of primary and alternate registers (result in primary) - */ -void ob_or(void) -{ - stgwrite("\tor\n"); - code_idx+=opcodes(1); -} - -/* - * "exclusive or" of primary and alternate registers (result in primary) - */ -void ob_xor(void) -{ - stgwrite("\txor\n"); - code_idx+=opcodes(1); -} - -/* - * "and" of primary and secundairy registers (result in primary) - */ -void ob_and(void) -{ - stgwrite("\tand\n"); - code_idx+=opcodes(1); -} - -/* - * test ALT==PRI; result in primary register (1 or 0). - */ -void ob_eq(void) -{ - stgwrite("\teq\n"); - code_idx+=opcodes(1); -} - -/* - * test ALT!=PRI - */ -void ob_ne(void) -{ - stgwrite("\tneq\n"); - code_idx+=opcodes(1); -} - -/* The abstract machine defines the relational instructions so that PRI is - * on the left side and ALT on the right side of the operator. For example, - * SLESS sets PRI to either 1 or 0 depending on whether the expression - * "PRI < ALT" is true. - * - * The compiler generates comparisons with ALT on the left side of the - * relational operator and PRI on the right side. The XCHG instruction - * prefixing the relational operators resets this. We leave it to the - * peephole optimizer to choose more compact instructions where possible. - */ - -/* Relational operator prefix for chained relational expressions. The - * "suffix" code restores the stack. - * For chained relational operators, the goal is to keep the comparison - * result "so far" in PRI and the value of the most recent operand in - * ALT, ready for a next comparison. - * The "prefix" instruction pushed the comparison result (PRI) onto the - * stack and moves the value of ALT into PRI. If there is a next comparison, - * PRI can now serve as the "left" operand of the relational operator. - */ -void relop_prefix(void) -{ - stgwrite("\tpush.pri\n"); - stgwrite("\tmove.pri\n"); - code_idx+=opcodes(2); -} - -void relop_suffix(void) -{ - stgwrite("\tswap.alt\n"); - stgwrite("\tand\n"); - stgwrite("\tpop.alt\n"); - code_idx+=opcodes(3); -} - -/* - * test ALTPRI (signed) - */ -void os_gt(void) -{ - stgwrite("\txchg\n"); - stgwrite("\tsgrtr\n"); - code_idx+=opcodes(2); -} - -/* - * test ALT>=PRI (signed) - */ -void os_ge(void) -{ - stgwrite("\txchg\n"); - stgwrite("\tsgeq\n"); - code_idx+=opcodes(2); -} - -/* - * logical negation of primary register - */ -void lneg(void) -{ - stgwrite("\tnot\n"); - code_idx+=opcodes(1); -} - -/* - * two's complement primary register - */ -void neg(void) -{ - stgwrite("\tneg\n"); - code_idx+=opcodes(1); -} - -/* - * one's complement of primary register - */ -void invert(void) -{ - stgwrite("\tinvert\n"); - code_idx+=opcodes(1); -} - -/* - * nop - */ -void nooperation(void) -{ - stgwrite("\tnop\n"); - code_idx+=opcodes(1); -} - -void inc_pri() -{ - stgwrite("\tinc.pri\n"); - code_idx+=opcodes(1); -} - -void dec_pri() -{ - stgwrite("\tdec.pri\n"); - code_idx+=opcodes(1); -} - -/* increment symbol - */ -void inc(value *lval) -{ - symbol *sym; - - sym=lval->sym; - if (lval->ident==iARRAYCELL) { - /* indirect increment, address already in PRI */ - stgwrite("\tinc.i\n"); - code_idx+=opcodes(1); - } else if (lval->ident==iARRAYCHAR) { - /* indirect increment of single character, address already in PRI */ - stgwrite("\tpush.pri\n"); - stgwrite("\tpush.alt\n"); - stgwrite("\tmove.alt\n"); /* copy address */ - stgwrite("\tlodb.i "); /* read from PRI into PRI */ - outval(sCHARBITS/8,TRUE); /* read one or two bytes */ - stgwrite("\tinc.pri\n"); - stgwrite("\tstrb.i "); /* write PRI to ALT */ - outval(sCHARBITS/8,TRUE); /* write one or two bytes */ - stgwrite("\tpop.alt\n"); - stgwrite("\tpop.pri\n"); - code_idx+=opcodes(8)+opargs(2); - } else if (lval->ident==iREFERENCE) { - assert(sym!=NULL); - stgwrite("\tpush.pri\n"); - /* load dereferenced value */ - assert(sym->vclass==sLOCAL); /* global references don't exist in Pawn */ - if (sym->vclass==sLOCAL) - stgwrite("\tlref.s.pri "); - else - stgwrite("\tlref.pri "); - outval(sym->addr,TRUE); - /* increment */ - stgwrite("\tinc.pri\n"); - /* store dereferenced value */ - if (sym->vclass==sLOCAL) - stgwrite("\tsref.s.pri "); - else - stgwrite("\tsref.pri "); - outval(sym->addr,TRUE); - stgwrite("\tpop.pri\n"); - code_idx+=opcodes(5)+opargs(2); - } else { - /* local or global variable */ - assert(sym!=NULL); - if (sym->vclass==sLOCAL) - stgwrite("\tinc.s "); - else - stgwrite("\tinc "); - outval(sym->addr,TRUE); - code_idx+=opcodes(1)+opargs(1); - } /* if */ -} - -/* decrement symbol - * - * in case of an integer pointer, the symbol must be incremented by 2. - */ -void dec(value *lval) -{ - symbol *sym; - - sym=lval->sym; - if (lval->ident==iARRAYCELL) { - /* indirect decrement, address already in PRI */ - stgwrite("\tdec.i\n"); - code_idx+=opcodes(1); - } else if (lval->ident==iARRAYCHAR) { - /* indirect decrement of single character, address already in PRI */ - stgwrite("\tpush.pri\n"); - stgwrite("\tpush.alt\n"); - stgwrite("\tmove.alt\n"); /* copy address */ - stgwrite("\tlodb.i "); /* read from PRI into PRI */ - outval(sCHARBITS/8,TRUE); /* read one or two bytes */ - stgwrite("\tdec.pri\n"); - stgwrite("\tstrb.i "); /* write PRI to ALT */ - outval(sCHARBITS/8,TRUE); /* write one or two bytes */ - stgwrite("\tpop.alt\n"); - stgwrite("\tpop.pri\n"); - code_idx+=opcodes(8)+opargs(2); - } else if (lval->ident==iREFERENCE) { - assert(sym!=NULL); - stgwrite("\tpush.pri\n"); - /* load dereferenced value */ - assert(sym->vclass==sLOCAL); /* global references don't exist in Pawn */ - if (sym->vclass==sLOCAL) - stgwrite("\tlref.s.pri "); - else - stgwrite("\tlref.pri "); - outval(sym->addr,TRUE); - /* decrement */ - stgwrite("\tdec.pri\n"); - /* store dereferenced value */ - if (sym->vclass==sLOCAL) - stgwrite("\tsref.s.pri "); - else - stgwrite("\tsref.pri "); - outval(sym->addr,TRUE); - stgwrite("\tpop.pri\n"); - code_idx+=opcodes(5)+opargs(2); - } else { - /* local or global variable */ - assert(sym!=NULL); - if (sym->vclass==sLOCAL) - stgwrite("\tdec.s "); - else - stgwrite("\tdec "); - outval(sym->addr,TRUE); - code_idx+=opcodes(1)+opargs(1); - } /* if */ -} - -/* - * Jumps to "label" if PRI != 0 - */ -void jmp_ne0(int number) -{ - stgwrite("\tjnz "); - outval(number,TRUE); - code_idx+=opcodes(1)+opargs(1); -} - -/* - * Jumps to "label" if PRI == 0 - */ -void jmp_eq0(int number) -{ - stgwrite("\tjzer "); - outval(number,TRUE); - code_idx+=opcodes(1)+opargs(1); -} - -/* write a value in hexadecimal; optionally adds a newline */ -void outval(cell val,int newline) -{ - stgwrite(itoh(val)); - if (newline) - stgwrite("\n"); -} - -void invoke_getter(methodmap_method_t *method) -{ - if (!method->getter) { - error(149, method->name); - return; - } - - // push.c 1 - // sysreq.c N 1 - // stack 8 - pushreg(sPRI); - pushval(1); - ffcall(method->getter, NULL, 1); - - if (sc_status != statSKIP) - markusage(method->getter, uREAD); -} - -void invoke_setter(methodmap_method_t *method, int save) -{ - if (!method->setter) { - error(152, method->name); - return; - } - - if (save) - pushreg(sPRI); - pushreg(sPRI); - pushreg(sALT); - pushval(2); - ffcall(method->setter, NULL, 2); - if (save) - popreg(sPRI); - - if (sc_status != statSKIP) - markusage(method->setter, uREAD); -} - -// function value -> pri -void load_glbfn(symbol *sym) -{ - assert(sym->ident == iFUNCTN); - assert(!(sym->usage & uNATIVE)); - stgwrite("\tldgfn.pri "); - stgwrite(sym->name); - stgwrite("\n"); - code_idx += opcodes(1) + opargs(1); - - if (sc_status != statSKIP) - markusage(sym, uREAD); -} diff --git a/sourcepawn/compiler/sc5-in.scp b/sourcepawn/compiler/sc5-in.scp deleted file mode 100644 index 7bed79f8..00000000 --- a/sourcepawn/compiler/sc5-in.scp +++ /dev/null @@ -1,272 +0,0 @@ -/* Pawn compiler - Error message strings (plain and compressed formats) - * - * Copyright (c) ITB CompuPhase, 2000-2006 - * - * This software is provided "as-is", without any express or implied warranty. - * In no event will the authors be held liable for any damages arising from - * the use of this software. - * - * Permission is granted to anyone to use this software for any purpose, - * including commercial applications, and to alter it and redistribute it - * freely, subject to the following restrictions: - * - * 1. The origin of this software must not be misrepresented; you must not - * claim that you wrote the original software. If you use this software in - * a product, an acknowledgment in the product documentation would be - * appreciated but is not required. - * 2. Altered source versions must be plainly marked as such, and must not be - * misrepresented as being the original software. - * 3. This notice may not be removed or altered from any source distribution. - * - * Version: $Id$ - */ - -static const char *errmsg[] = { -/*001*/ "expected token: \"%s\", but found \"%s\"\n", -/*002*/ "only a single statement (or expression) can follow each \"case\"\n", -/*003*/ "declaration of a local variable must appear in a compound block\n", -/*004*/ "function \"%s\" is not implemented\n", -/*005*/ "function may not have arguments\n", -/*006*/ "must be assigned to an array\n", -/*007*/ "operator cannot be redefined\n", -/*008*/ "must be a constant expression; assumed zero\n", -/*009*/ "invalid array size (negative, zero or out of bounds)\n", -/*010*/ "invalid function or declaration\n", -/*011*/ "invalid outside functions\n", -/*012*/ "invalid function call, not a valid address\n", -/*013*/ "no entry point (no public functions)\n", -/*014*/ "invalid statement; not in switch\n", -/*015*/ "\"default\" case must be the last case in switch statement\n", -/*016*/ "multiple defaults in \"switch\"\n", -/*017*/ "undefined symbol \"%s\"\n", -/*018*/ "initialization data exceeds declared size\n", -/*019*/ "not a label: \"%s\"\n", -/*020*/ "invalid symbol name \"%s\"\n", -/*021*/ "symbol already defined: \"%s\"\n", -/*022*/ "must be lvalue (non-constant)\n", -/*023*/ "array assignment must be simple assignment\n", -/*024*/ "\"break\" or \"continue\" is out of context\n", -/*025*/ "function heading differs from prototype\n", -/*026*/ "no matching \"#if...\"\n", -/*027*/ "invalid character constant\n", -/*028*/ "invalid subscript (not an array or too many subscripts): \"%s\"\n", -/*029*/ "invalid expression, assumed zero\n", -/*030*/ "compound statement not closed at the end of file (started at line %d)\n", -/*031*/ "unknown directive\n", -/*032*/ "array index out of bounds (variable \"%s\")\n", -/*033*/ "array must be indexed (variable \"%s\")\n", -/*034*/ "argument does not have a default value (argument %d)\n", -/*035*/ "argument type mismatch (argument %d)\n", -/*036*/ "empty statement\n", -/*037*/ "invalid string (possibly non-terminated string)\n", -/*038*/ "extra characters on line\n", -/*039*/ "constant symbol has no size\n", -/*040*/ "duplicate \"case\" label (value %d)\n", -/*041*/ "invalid ellipsis, array size is not known\n", -/*042*/ "invalid combination of class specifiers\n", -/*043*/ "character constant exceeds range for packed string\n", -/*044*/ "positional parameters must precede all named parameters\n", -/*045*/ "too many function arguments\n", -/*046*/ "unknown array size (variable \"%s\")\n", -/*047*/ "array sizes do not match, or destination array is too small\n", -/*048*/ "array (s do not match\n", -/*049*/ "invalid line continuation\n", -/*050*/ "invalid range\n", -/*051*/ "invalid subscript, use \"[ ]\" operators on major dimensions\n", -/*052*/ "multi-dimensional arrays must be fully initialized\n", -/*053*/ "exceeding maximum number of dimensions\n", -/*054*/ "unmatched closing brace (\"}\")\n", -/*055*/ "start of function body without function header\n", -/*056*/ "arrays, local variables and function arguments cannot be public (variable \"%s\")\n", -/*057*/ "unfinished expression before compiler directive\n", -/*058*/ "duplicate argument; same argument is passed twice\n", -/*059*/ "function argument may not have a default value (variable \"%s\")\n", -/*060*/ "multiple \"#else\" directives between \"#if ... #endif\"\n", -/*061*/ "\"#elseif\" directive follows an \"#else\" directive\n", -/*062*/ "number of operands does not fit the operator\n", -/*063*/ "function result tag of operator \"%s\" must be \"%s\"\n", -/*064*/ "cannot change predefined operators\n", -/*065*/ "function argument may only have a single tag (argument %d)\n", -/*066*/ "function argument may not be a reference argument or an array (argument \"%s\")\n", -/*067*/ "variable cannot be both a reference and an array (variable \"%s\")\n", -/*068*/ "invalid rational number precision in #pragma\n", -/*069*/ "rational number format already defined\n", -/*070*/ "rational number support was not enabled\n", -/*071*/ "user-defined operator must be declared before use (function \"%s\")\n", -/*072*/ "\"sizeof\" operator is invalid on \"function\" symbols\n", -/*073*/ "function argument must be an array (argument \"%s\")\n", -/*074*/ "#define pattern must start with an alphabetic character\n", -/*075*/ "input line too long (after substitutions)\n", -/*076*/ "syntax error in the expression, or invalid function call\n", -/*077*/ "malformed UTF-8 encoding, or corrupted file: %s\n", -/*078*/ "function uses both \"return\" and \"return \"\n", -/*079*/ "inconsistent return types (array & non-array)\n", -/*080*/ "unknown symbol, or not a constant symbol (symbol \"%s\")\n", -/*081*/ "cannot take a tag as a default value for an indexed array parameter (symbol \"%s\")\n", -/*082*/ "user-defined operators and native functions may not have states\n", -/*083*/ "a function or variable may only belong to a single automaton (symbol \"%s\")\n", -/*084*/ "state conflict: one of the states is already assigned to another implementation (symbol \"%s\")\n", -/*085*/ "no states are defined for symbol \"%s\"\n", -/*086*/ "unknown automaton \"%s\"\n", -/*087*/ "unknown state \"%s\" for automaton \"%s\"\n", -/*088*/ "public variables and local variables may not have states (symbol \"%s\")\n", -/*089*/ "state variables may not be initialized (symbol \"%s\")\n", -/*090*/ "public functions may not return arrays (symbol \"%s\")\n", -/*091*/ "ambiguous constant; tag override is required (symbol \"%s\")\n", -/*092*/ "number of arguments does not match definition\n", -/*093*/ "expected tag name identifier\n", -/*094*/ "function enumeration requires unique tag\n", -/*095*/ "cannot have required parameters after optional parameters\n", -/*096*/ "could not find member \"%s\" in struct \"%s\"\n", -/*097*/ "symbol \"%s\" does not have a matching type\n", -/*098*/ "type \"%s\" should be \"%s\" in new-style declarations\n", -/*099*/ "%s should not have an explicit return type\n", -/*100*/ "function prototypes do not match\n", -/*101*/ "specify either all dimensions or only the last dimension\n", -/*102*/ "cannot find %s %s\n", -/*103*/ "%s was already defined on this %s\n", -/*104*/ "cannot find any methods for %s\n", -/*105*/ "cannot find method or property %s.%s\n", -/*106*/ "cannot call methods on an array\n", -/*107*/ "cannot call methods on a function\n", -/*108*/ "method must have a first argument compatible with the %s type (%s)\n", -/*109*/ "%s name must start with an uppercase letter\n", -/*110*/ "%s has already been defined (previously seen as %s)\n", -/*111*/ "expected identifier - did you forget a type?\n", -/*112*/ "constructor function must return tag %s\n", -/*113*/ "constructor for \"%s\" already exists\n", -/*114*/ "missing type, or %s must have the same name as %s \"%s\"\n", -/*115*/ "cannot use delete, %s %s has no destructor\n", -/*116*/ "no methodmap or class was found for %s\n", -/*117*/ "no destructor was found for %s %s\n", -/*118*/ "destructors must be native functions\n", -/*119*/ "destructors cannot have extra arguments\n", -/*120*/ "methodmap and class signatures must use new-style type declarations\n", -/*121*/ "cannot specify array dimensions on both type and name\n", -/*122*/ "expected type expression\n", -/*123*/ "fully-qualified name \"%s\" is too long, would be truncated to \"%s\"\n", -/*124*/ "unexpected token, expected method or property\n", -/*125*/ "expected \"native\", \"get\", or \"set\"\n", -/*126*/ "%s for %s already exists\n", -/*127*/ "property getters cannot accept extra arguments\n", -/*128*/ "%s must have the same return type as property %s (%s)\n", -/*129*/ "cannot mix methodmaps and classes with inheritance\n", -/*130*/ "cannot coerce functions to values\n", -/*131*/ "cannot coerce object type %s to non-object type %s\n", -/*132*/ "cannot coerce non-object type %s to object type %s\n", -/*133*/ "cannot coerce unrelated object types %s and %s\n", -/*134*/ "type mismatch (%s and %s)\n", -/*135*/ "cannot use an object in a multi-tag selector\n", -/*136*/ "arrays are not supported as return types\n", -/*137*/ "cannot mix reference and array types\n", -/*138*/ "const was specified twice\n", -/*139*/ "could not find type \"%s\"\n", -/*140*/ "new-style array types cannot specify dimension sizes as part of their type\n", -/*141*/ "natives, forwards, and public functions cannot return arrays\n", -/*142*/ "invalid type declaration\n", -/*143*/ "new-style declarations should not have \"new\"\n", -/*144*/ "void cannot be used as a variable type\n", -/*145*/ "invalid type expression\n", -/*146*/ "#pragma newdecls must be required or optional\n", -/*147*/ "new-style declarations are required\n", -/*148*/ "cannot assign null to a non-nullable type\n", -/*149*/ "no getter found for property %s\n", -/*150*/ "setter must take exactly one extra argument with type %s\n", -/*151*/ "setter must return void\n", -/*152*/ "no setter found for property %s\n", -/*153*/ "cannot use non-public functions as callbacks\n", -/*154*/ "cannot assign INVALID_FUNCTION to a non-function type\n", -/*155*/ "expected newline, but found '%s'\n", -/*156*/ "unused156\n", -/*157*/ "'%s' is a reserved keyword\n", -/*158*/ "multi-tags are no longer supported\n", -/*159*/ "brackets after variable name indicate a fixed-size array, but size could not be determined - either specify sizes, an array initializer, or use dynamic syntax (such as 'char[] x')\n", -/*160*/ "brackets in between type and variable name indicate a dynamic-size array, but a fixed-size initializer was given\n", -/*161*/ "brackets after variable name indicate a fixed-size array, but a dynamic size was given - did you mean to use 'new %s[size]' syntax?\n", -/*162*/ "cannot create dynamic arrays in global scope - did you mean to create a fixed-length array with brackets after the variable name?\n", -/*163*/ "indeterminate array size in \"sizeof\" expression (symbol \"%s\")\n", -/*164*/ "allocated array type '%s' doesn't match original type '%s'\n", -/*165*/ "cannot create dynamic arrays in static scope - did you mean to create a fixed-length array with brackets after the variable name?\n", -/*166*/ "cannot use 'this' outside of a methodmap method or property\n", -/*167*/ "cannot use delete, %s do not have destructors\n", -/*168*/ "re-tagging enums is no longer supported\n", -/*169*/ "cannot tag an enum as implicit-int\n", -/*170*/ "creating new object '%s' requires using 'new' before its constructor\n", -/*171*/ "cannot use 'new' with non-object-like methodmap '%s'\n", -/*172*/ "methodmap '%s' does not have a constructor\n", -/*173*/ "'%s' is a newly reserved keyword that may be used in the future; use a different name as an identifier\n", -/*174*/ "symbol '%s' is a type and cannot be used as a value\n", -/*175*/ "constructors cannot be static\n", -/*176*/ "non-static method or property '%s' must be called with a value of type '%s'\n", -/*177*/ "static method '%s' must be invoked via its type (try '%s.%s')\n", -/*178*/ "cannot coerce %s[] to %s[]; storage classes differ\n", -/*179*/ "cannot assign %s[] to %s[], storage classes differ\n", -/*180*/ "function return type differs from prototype. expected '%s', but got '%s'\n", -/*181*/ "function argument named '%s' differs from prototype\n", -/*182*/ "functions that return arrays cannot be used as callbacks\n", -}; - -static const char *fatalmsg[] = { -/*182*/ "cannot read from file: \"%s\"\n", -/*183*/ "cannot write to file: \"%s\"\n", -/*184*/ "table overflow: \"%s\"\n", - /* table can be: loop table - * literal table - * staging buffer - * option table (response file) - * peephole optimizer table - */ -/*185*/ "insufficient memory\n", -/*186*/ "invalid assembler instruction \"%s\"\n", -/*187*/ "numeric overflow, exceeding capacity\n", -/*188*/ "compiled script exceeds the maximum memory size (%ld bytes)\n", -/*189*/ "too many error messages on one line\n", -/*190*/ "codepage mapping file not found\n", -/*191*/ "invalid path: \"%s\"\n", -/*192*/ "assertion failed: %s\n", -/*193*/ "user error: %s\n", -}; - -static const char *warnmsg[] = { -/*200*/ "symbol \"%s\" is truncated to %d characters\n", -/*201*/ "redefinition of constant/macro (symbol \"%s\")\n", -/*202*/ "number of arguments does not match definition\n", -/*203*/ "symbol is never used: \"%s\"\n", -/*204*/ "symbol is assigned a value that is never used: \"%s\"\n", -/*205*/ "redundant code: constant expression is zero\n", -/*206*/ "redundant test: constant expression is non-zero\n", -/*207*/ "unknown #pragma\n", -/*208*/ "function with tag result used before definition, forcing reparse\n", -/*209*/ "function \"%s\" should return a value\n", -/*210*/ "possible use of symbol before initialization: \"%s\"\n", -/*211*/ "possibly unintended assignment\n", -/*212*/ "possibly unintended bitwise operation\n", -/*213*/ "tag mismatch\n", -/*214*/ "possibly a \"const\" array argument was intended: \"%s\"\n", -/*215*/ "expression has no effect\n", -/*216*/ "nested comment\n", -/*217*/ "loose indentation\n", -/*218*/ "old style prototypes used with optional semicolumns\n", -/*219*/ "local variable \"%s\" shadows a variable at a preceding level\n", -/*220*/ "expression with tag override must appear between parentheses\n", -/*221*/ "label name \"%s\" shadows tag name\n", -/*222*/ "number of digits exceeds rational number precision\n", -/*223*/ "redundant \"sizeof\": argument size is always 1 (symbol \"%s\")\n", -/*224*/ "unused\n", -/*225*/ "unreachable code\n", -/*226*/ "a variable is assigned to itself (symbol \"%s\")\n", -/*227*/ "more initializers than enum fields\n", -/*228*/ "length of initializer exceeds size of the enum field\n", -/*229*/ "index tag mismatch (symbol \"%s\")\n", -/*230*/ "no implementation for state \"%s\" in function \"%s\", no fall-back\n", -/*231*/ "state specification on forward declaration is ignored\n", -/*232*/ "output file is written, but with compact encoding disabled\n", -/*233*/ "state variable \"%s\" shadows a global variable\n", -/*234*/ "symbol \"%s\" is marked as deprecated: %s\n", -/*235*/ "public function lacks forward declaration (symbol \"%s\")\n", -/*236*/ "unknown parameter in substitution (incorrect #define pattern)\n", -/*237*/ "coercing functions to and from primitives is unsupported and will be removed in the future\n", -/*238*/ "'%s:' is an illegal cast; use view_as<%s>(expression)\n", -/*239*/ "'%s' is an illegal tag; use %s as a type\n", -/*240*/ "'%s:' is an old-style tag operation; use view_as<%s>(expression) instead\n", -}; diff --git a/sourcepawn/compiler/sc5.cpp b/sourcepawn/compiler/sc5.cpp deleted file mode 100644 index 6520a8cf..00000000 --- a/sourcepawn/compiler/sc5.cpp +++ /dev/null @@ -1,243 +0,0 @@ -// vim: set ts=8 sts=2 sw=2 tw=99 et: -/* Pawn compiler - Error message system - * In fact a very simple system, using only 'panic mode'. - * - * Copyright (c) ITB CompuPhase, 1997-2006 - * - * This software is provided "as-is", without any express or implied warranty. - * In no event will the authors be held liable for any damages arising from - * the use of this software. - * - * Permission is granted to anyone to use this software for any purpose, - * including commercial applications, and to alter it and redistribute it - * freely, subject to the following restrictions: - * - * 1. The origin of this software must not be misrepresented; you must not - * claim that you wrote the original software. If you use this software in - * a product, an acknowledgment in the product documentation would be - * appreciated but is not required. - * 2. Altered source versions must be plainly marked as such, and must not be - * misrepresented as being the original software. - * 3. This notice may not be removed or altered from any source distribution. - * - * Version: $Id$ - */ -#include -#if defined __WIN32__ || defined _WIN32 || defined __MSDOS__ - #include -#endif -#if defined LINUX || defined __GNUC__ - #include -#endif -#include -#include -#include /* ANSI standardized variable argument list functions */ -#include -#if defined FORTIFY - #include -#endif -#include "sc.h" - -#if defined _MSC_VER - #pragma warning(push) - #pragma warning(disable:4125) /* decimal digit terminates octal escape sequence */ -#endif - -#include "sc5-in.scp" - -#if defined _MSC_VER - #pragma warning(pop) -#endif - -#define NUM_WARNINGS (int)(sizeof warnmsg / sizeof warnmsg[0]) -static unsigned char warndisable[(NUM_WARNINGS + 7) / 8]; /* 8 flags in a char */ - -static int errflag; -static int errstart; /* line number at which the instruction started */ -static int sErrLine; /* forced line number for the error message */ - -/* error - * - * Outputs an error message (note: msg is passed optionally). - * If an error is found, the variable "errflag" is set and subsequent - * errors are ignored until lex() finds a semicolumn or a keyword - * (lex() resets "errflag" in that case). - * - * Global references: inpfname (reffered to only) - * fline (reffered to only) - * fcurrent (reffered to only) - * errflag (altered) - */ -int error(int number,...) -{ -static const char *prefix[3]={ "error", "fatal error", "warning" }; -static int lastline,errorcount; -static short lastfile; - const char *msg,*pre; - va_list argptr; - - // sErrLine is used to temporarily change the line number of reported errors. - // Pawn has an upstream bug where this is not reset on early-return, which - // can lead to broken line numbers in error messages. - int errline = sErrLine; - sErrLine = -1; - - bool is_warning = (number >= 200 && !sc_warnings_are_errors); - - /* errflag is reset on each semicolon. - * In a two-pass compiler, an error should not be reported twice. Therefore - * the error reporting is enabled only in the second pass (and only when - * actually producing output). Fatal errors may never be ignored. - */ - int not_fatal = (number < FIRST_FATAL_ERROR || number >= 200); - if (errflag && not_fatal) - return 0; - if (sc_status != statWRITE && not_fatal) { - if (!sc_err_status) - return 0; - } - - /* also check for disabled warnings */ - if (number>=200) { - int index=(number-200)/8; - int mask=1 << ((number-200)%8); - if ((warndisable[index] & mask)!=0) - return 0; - } /* if */ - - if (number0) - errstart=errline; - else - errline=fline; - assert(errstart<=errline); - va_start(argptr,number); - if (strlen(errfname)==0) { - int start= (errstart==errline) ? -1 : errstart; - if (pc_error(number,msg,inpfname,start,errline,argptr)) { - if (outf!=NULL) { - pc_closeasm(outf,TRUE); - outf=NULL; - } /* if */ - longjmp(errbuf,3); /* user abort */ - } /* if */ - } else { - FILE *fp=fopen(errfname,"a"); - if (fp!=NULL) { - if (errstart>=0 && errstart!=errline) - fprintf(fp,"%s(%d -- %d) : %s %03d: ",inpfname,errstart,errline,pre,number); - else - fprintf(fp,"%s(%d) : %s %03d: ",inpfname,errline,pre,number); - vfprintf(fp,msg,argptr); - fclose(fp); - } /* if */ - } /* if */ - va_end(argptr); - - if ((number>=FIRST_FATAL_ERROR && number<200) || errnum>25){ - if (strlen(errfname)==0) { - va_start(argptr,number); - pc_error(0,"\nCompilation aborted.",NULL,0,0,argptr); - va_end(argptr); - } /* if */ - if (outf!=NULL) { - pc_closeasm(outf,TRUE); - outf=NULL; - } /* if */ - longjmp(errbuf,2); /* fatal error, quit */ - } /* if */ - - /* check whether we are seeing many errors on the same line */ - if ((errstart<0 && lastline!=fline) || lastlinefline || fcurrent!=lastfile) - errorcount=0; - lastline=fline; - lastfile=fcurrent; - if (!is_warning) - errorcount++; - if (errorcount>=3) - error(FATAL_ERROR_OVERWHELMED_BY_BAD); - - return 0; -} - -void errorset(int code,int line) -{ - switch (code) { - case sRESET: - errflag=FALSE; /* start reporting errors */ - break; - case sFORCESET: - errflag=TRUE; /* stop reporting errors */ - break; - case sEXPRMARK: - errstart=fline; /* save start line number */ - break; - case sEXPRRELEASE: - errstart=-1; /* forget start line number */ - sErrLine=-1; - break; - case sSETPOS: - sErrLine=line; - break; - } /* switch */ -} - -/* sc_enablewarning() - * Enables or disables a warning (errors cannot be disabled). - * Initially all warnings are enabled. The compiler does this by setting bits - * for the *disabled* warnings and relying on the array to be zero-initialized. - * - * Parameter enable can be: - * o 0 for disable - * o 1 for enable - * o 2 for toggle - */ -int pc_enablewarning(int number,int enable) -{ - int index; - unsigned char mask; - - if (number<200) - return FALSE; /* errors and fatal errors cannot be disabled */ - number -= 200; - if (number>=NUM_WARNINGS) - return FALSE; - - index=number/8; - mask=(unsigned char)(1 << (number%8)); - switch (enable) { - case 0: - warndisable[index] |= mask; - break; - case 1: - warndisable[index] &= (unsigned char)~mask; - break; - case 2: - warndisable[index] ^= mask; - break; - } /* switch */ - - return TRUE; -} - -#undef SCPACK_TABLE diff --git a/sourcepawn/compiler/sc6.cpp b/sourcepawn/compiler/sc6.cpp deleted file mode 100644 index bb6e9662..00000000 --- a/sourcepawn/compiler/sc6.cpp +++ /dev/null @@ -1,1045 +0,0 @@ -// vim: set sts=2 ts=8 sw=2 tw=99 et: -/* Pawn compiler - Binary code generation (the "assembler") - * - * Copyright (c) ITB CompuPhase, 1997-2006 - * - * This software is provided "as-is", without any express or implied warranty. - * In no event will the authors be held liable for any damages arising from - * the use of this software. - * - * Permission is granted to anyone to use this software for any purpose, - * including commercial applications, and to alter it and redistribute it - * freely, subject to the following restrictions: - * - * 1. The origin of this software must not be misrepresented; you must not - * claim that you wrote the original software. If you use this software in - * a product, an acknowledgment in the product documentation would be - * appreciated but is not required. - * 2. Altered source versions must be plainly marked as such, and must not be - * misrepresented as being the original software. - * 3. This notice may not be removed or altered from any source distribution. - * - * Version: $Id$ - */ -#include -#include -#include /* for macro max() */ -#include /* for macro offsetof() */ -#include -#include -#if defined FORTIFY - #include -#endif -#include "lstring.h" -#include "sc.h" -#include "amxdbg.h" -#if defined LINUX || defined __FreeBSD__ || defined __OpenBSD__ - #include "sclinux.h" -#endif -#include -#include -#include -#include -#include -#include "smx-builder.h" -#include "memory-buffer.h" - -using namespace sp; -using namespace ke; - -typedef cell (*OPCODE_PROC)(Vector *buffer, char *params, cell opcode); - -typedef struct { - cell opcode; - const char *name; - int segment; /* sIN_CSEG=parse in cseg, sIN_DSEG=parse in dseg */ - OPCODE_PROC func; -} OPCODEC; - -static cell codeindex; /* similar to "code_idx" */ -static cell *LabelTable; /* label table */ -static int writeerror; -static int bytes_in, bytes_out; -static jmp_buf compact_err; - -/* apparently, strtol() does not work correctly on very large (unsigned) - * hexadecimal values */ -static ucell hex2long(const char *s,char **n) -{ - ucell result=0L; - int negate=FALSE; - int digit; - - /* ignore leading whitespace */ - while (*s==' ' || *s=='\t') - s++; - - /* allow a negation sign to create the two's complement of numbers */ - if (*s=='-') { - negate=TRUE; - s++; - } /* if */ - - assert((*s>='0' && *s<='9') || (*s>='a' && *s<='f') || (*s>='a' && *s<='f')); - for ( ;; ) { - if (*s>='0' && *s<='9') - digit=*s-'0'; - else if (*s>='a' && *s<='f') - digit=*s-'a' + 10; - else if (*s>='A' && *s<='F') - digit=*s-'A' + 10; - else - break; /* probably whitespace */ - result=(result<<4) | digit; - s++; - } /* for */ - if (n!=NULL) - *n=(char*)s; - if (negate) - result=(~result)+1; /* take two's complement of the result */ - return (ucell)result; -} - -static ucell getparam(const char *s,char **n) -{ - ucell result=0; - for ( ;; ) { - result+=hex2long(s,(char**)&s); - if (*s!='+') - break; - s++; - } /* for */ - if (n!=NULL) - *n=(char*)s; - return result; -} - -static char *skipwhitespace(char *str) -{ - while (isspace(*str)) - str++; - return str; -} - -static char *stripcomment(char *str) -{ - char *ptr=strchr(str,';'); - if (ptr!=NULL) { - *ptr++='\n'; /* terminate the line, but leave the '\n' */ - *ptr='\0'; - } /* if */ - return str; -} - -static cell noop(Vector *buffer, char *params, cell opcode) -{ - return 0; -} - -static cell set_currentfile(Vector *buffer, char *params, cell opcode) -{ - fcurrent=(short)getparam(params,NULL); - return 0; -} - -static cell parm0(Vector *buffer, char *params, cell opcode) -{ - if (buffer) - buffer->append(opcode); - return opcodes(1); -} - -static cell parm1(Vector *buffer, char *params, cell opcode) -{ - ucell p = getparam(params, nullptr); - if (buffer) { - buffer->append(opcode); - buffer->append(p); - } - return opcodes(1) + opargs(1); -} - -static cell parm2(Vector *buffer, char *params, cell opcode) -{ - ucell p1 = getparam(params, ¶ms); - ucell p2 = getparam(params, nullptr); - if (buffer) { - buffer->append(opcode); - buffer->append(p1); - buffer->append(p2); - } - return opcodes(1) + opargs(2); -} - -static cell parm3(Vector *buffer, char *params, cell opcode) -{ - ucell p1 = getparam(params, ¶ms); - ucell p2 = getparam(params, ¶ms); - ucell p3 = getparam(params, nullptr); - if (buffer) { - buffer->append(opcode); - buffer->append(p1); - buffer->append(p2); - buffer->append(p3); - } - return opcodes(1) + opargs(3); -} - -static cell parm4(Vector *buffer, char *params, cell opcode) -{ - ucell p1 = getparam(params, ¶ms); - ucell p2 = getparam(params, ¶ms); - ucell p3 = getparam(params, ¶ms); - ucell p4 = getparam(params, nullptr); - if (buffer) { - buffer->append(opcode); - buffer->append(p1); - buffer->append(p2); - buffer->append(p3); - buffer->append(p4); - } - return opcodes(1) + opargs(4); -} - -static cell parm5(Vector *buffer, char *params, cell opcode) -{ - ucell p1 = getparam(params, ¶ms); - ucell p2 = getparam(params, ¶ms); - ucell p3 = getparam(params, ¶ms); - ucell p4 = getparam(params, ¶ms); - ucell p5 = getparam(params, nullptr); - if (buffer) { - buffer->append(opcode); - buffer->append(p1); - buffer->append(p2); - buffer->append(p3); - buffer->append(p4); - buffer->append(p5); - } - return opcodes(1) + opargs(5); -} - -static cell do_dump(Vector *buffer, char *params, cell opcode) -{ - int num = 0; - - while (*params != '\0') { - ucell p = getparam(params, ¶ms); - if (buffer) - buffer->append(p); - num++; - while (isspace(*params)) - params++; - } - return num * sizeof(cell); -} - -static cell do_ldgfen(Vector *buffer, char *params, cell opcode) -{ - char name[sNAMEMAX+1]; - - int i; - for (i=0; !isspace(*params); i++,params++) { - assert(*params != '\0'); - assert(i < sNAMEMAX); - name[i] = *params; - } - name[i]='\0'; - - symbol *sym = findglb(name, sGLOBAL); - assert(sym->ident == iFUNCTN); - assert(!(sym->usage & uNATIVE)); - assert((sym->funcid & 1) == 1); - - if (buffer) { - // Note: we emit const.pri for backward compatibility. - assert(opcode == sp::OP_UNGEN_LDGFN_PRI); - buffer->append(sp::OP_CONST_PRI); - buffer->append(sym->funcid); - } - return opcodes(1) + opargs(1); -} - -static cell do_call(Vector *buffer, char *params, cell opcode) -{ - char name[sNAMEMAX+1]; - - int i; - for (i=0; !isspace(*params); i++,params++) { - assert(*params != '\0'); - assert(i < sNAMEMAX); - name[i] = *params; - } - name[i]='\0'; - - cell p; - if (name[0] == 'l' && name[1] == '.') { - // Lookup the label address. - int val = (int)hex2long(name + 2, nullptr); - assert(val >= 0 && val < sc_labnum); - p = LabelTable[val]; - } else { - // Look up the function address; note that the correct file number must - // already have been set (in order for static globals to be found). - symbol *sym = findglb(name, sGLOBAL); - assert(sym->ident == iFUNCTN || sym->ident == iREFFUNC); - assert(sym->vclass == sGLOBAL); - p = sym->addr; - } - - if (buffer) { - buffer->append(opcode); - buffer->append(p); - } - return opcodes(1) + opargs(1); -} - -static cell do_jump(Vector *buffer, char *params, cell opcode) -{ - int i = (int)hex2long(params, nullptr); - assert(i >= 0 && i < sc_labnum); - - if (buffer) { - buffer->append(opcode); - buffer->append(LabelTable[i]); - } - return opcodes(1) + opargs(1); -} - -static cell do_switch(Vector *buffer, char *params, cell opcode) -{ - int i = (int)hex2long(params, nullptr); - assert(i >= 0 && i < sc_labnum); - - if (buffer) { - buffer->append(opcode); - buffer->append(LabelTable[i]); - } - return opcodes(1) + opargs(1); -} - -static cell do_case(Vector *buffer, char *params, cell opcode) -{ - cell v = hex2long(params ,¶ms); - int i = (int)hex2long(params, nullptr); - assert(i >= 0 && i < sc_labnum); - - if (buffer) { - buffer->append(v); - buffer->append(LabelTable[i]); - } - return opcodes(0) + opargs(2); -} - -static OPCODEC opcodelist[] = { - /* node for "invalid instruction" */ - { 0, NULL, 0, noop }, - /* opcodes in sorted order */ - { 78, "add", sIN_CSEG, parm0 }, - { 87, "add.c", sIN_CSEG, parm1 }, - { 14, "addr.alt", sIN_CSEG, parm1 }, - { 13, "addr.pri", sIN_CSEG, parm1 }, - { 30, "align.alt", sIN_CSEG, parm1 }, - { 29, "align.pri", sIN_CSEG, parm1 }, - { 81, "and", sIN_CSEG, parm0 }, - {121, "bounds", sIN_CSEG, parm1 }, - {137, "break", sIN_CSEG, parm0 }, /* version 8 */ - { 49, "call", sIN_CSEG, do_call }, - { 50, "call.pri", sIN_CSEG, parm0 }, - { 0, "case", sIN_CSEG, do_case }, - {130, "casetbl", sIN_CSEG, parm0 }, /* version 1 */ - {118, "cmps", sIN_CSEG, parm1 }, - { 0, "code", sIN_CSEG, set_currentfile }, - {156, "const", sIN_CSEG, parm2 }, /* version 9 */ - { 12, "const.alt", sIN_CSEG, parm1 }, - { 11, "const.pri", sIN_CSEG, parm1 }, - {157, "const.s", sIN_CSEG, parm2 }, /* version 9 */ - { 0, "data", sIN_DSEG, set_currentfile }, - {114, "dec", sIN_CSEG, parm1 }, - {113, "dec.alt", sIN_CSEG, parm0 }, - {116, "dec.i", sIN_CSEG, parm0 }, - {112, "dec.pri", sIN_CSEG, parm0 }, - {115, "dec.s", sIN_CSEG, parm1 }, - { 0, "dump", sIN_DSEG, do_dump }, - {166, "endproc", sIN_CSEG, parm0 }, - { 95, "eq", sIN_CSEG, parm0 }, - {106, "eq.c.alt", sIN_CSEG, parm1 }, - {105, "eq.c.pri", sIN_CSEG, parm1 }, -/*{124, "file", sIN_CSEG, do_file }, */ - {119, "fill", sIN_CSEG, parm1 }, - {162, "genarray", sIN_CSEG, parm1 }, - {163, "genarray.z", sIN_CSEG, parm1 }, - {100, "geq", sIN_CSEG, parm0 }, - { 99, "grtr", sIN_CSEG, parm0 }, - {120, "halt", sIN_CSEG, parm1 }, - { 45, "heap", sIN_CSEG, parm1 }, - { 27, "idxaddr", sIN_CSEG, parm0 }, - { 28, "idxaddr.b", sIN_CSEG, parm1 }, - {109, "inc", sIN_CSEG, parm1 }, - {108, "inc.alt", sIN_CSEG, parm0 }, - {111, "inc.i", sIN_CSEG, parm0 }, - {107, "inc.pri", sIN_CSEG, parm0 }, - {110, "inc.s", sIN_CSEG, parm1 }, - { 86, "invert", sIN_CSEG, parm0 }, - { 55, "jeq", sIN_CSEG, do_jump }, - { 60, "jgeq", sIN_CSEG, do_jump }, - { 59, "jgrtr", sIN_CSEG, do_jump }, - { 58, "jleq", sIN_CSEG, do_jump }, - { 57, "jless", sIN_CSEG, do_jump }, - { 56, "jneq", sIN_CSEG, do_jump }, - { 54, "jnz", sIN_CSEG, do_jump }, - { 52, "jrel", sIN_CSEG, parm1 }, /* always a number */ - { 64, "jsgeq", sIN_CSEG, do_jump }, - { 63, "jsgrtr", sIN_CSEG, do_jump }, - { 62, "jsleq", sIN_CSEG, do_jump }, - { 61, "jsless", sIN_CSEG, do_jump }, - { 51, "jump", sIN_CSEG, do_jump }, - {128, "jump.pri", sIN_CSEG, parm0 }, /* version 1 */ - { 53, "jzer", sIN_CSEG, do_jump }, - { 31, "lctrl", sIN_CSEG, parm1 }, - {167, "ldgfn.pri", sIN_CSEG, do_ldgfen }, - { 98, "leq", sIN_CSEG, parm0 }, - { 97, "less", sIN_CSEG, parm0 }, - { 25, "lidx", sIN_CSEG, parm0 }, - { 26, "lidx.b", sIN_CSEG, parm1 }, -/*{125, "line", sIN_CSEG, parm2 }, */ - { 2, "load.alt", sIN_CSEG, parm1 }, - {154, "load.both", sIN_CSEG, parm2 }, /* version 9 */ - { 9, "load.i", sIN_CSEG, parm0 }, - { 1, "load.pri", sIN_CSEG, parm1 }, - { 4, "load.s.alt", sIN_CSEG, parm1 }, - {155, "load.s.both",sIN_CSEG, parm2 }, /* version 9 */ - { 3, "load.s.pri", sIN_CSEG, parm1 }, - { 10, "lodb.i", sIN_CSEG, parm1 }, - { 6, "lref.alt", sIN_CSEG, parm1 }, - { 5, "lref.pri", sIN_CSEG, parm1 }, - { 8, "lref.s.alt", sIN_CSEG, parm1 }, - { 7, "lref.s.pri", sIN_CSEG, parm1 }, - { 34, "move.alt", sIN_CSEG, parm0 }, - { 33, "move.pri", sIN_CSEG, parm0 }, - {117, "movs", sIN_CSEG, parm1 }, - { 85, "neg", sIN_CSEG, parm0 }, - { 96, "neq", sIN_CSEG, parm0 }, - {134, "nop", sIN_CSEG, parm0 }, /* version 6 */ - { 84, "not", sIN_CSEG, parm0 }, - { 82, "or", sIN_CSEG, parm0 }, - { 43, "pop.alt", sIN_CSEG, parm0 }, - { 42, "pop.pri", sIN_CSEG, parm0 }, - { 46, "proc", sIN_CSEG, parm0 }, - { 40, "push", sIN_CSEG, parm1 }, - {133, "push.adr", sIN_CSEG, parm1 }, /* version 4 */ - { 37, "push.alt", sIN_CSEG, parm0 }, - { 39, "push.c", sIN_CSEG, parm1 }, - { 36, "push.pri", sIN_CSEG, parm0 }, - { 38, "push.r", sIN_CSEG, parm1 }, /* obsolete (never generated) */ - { 41, "push.s", sIN_CSEG, parm1 }, - {139, "push2", sIN_CSEG, parm2 }, /* version 9 */ - {141, "push2.adr", sIN_CSEG, parm2 }, /* version 9 */ - {138, "push2.c", sIN_CSEG, parm2 }, /* version 9 */ - {140, "push2.s", sIN_CSEG, parm2 }, /* version 9 */ - {143, "push3", sIN_CSEG, parm3 }, /* version 9 */ - {145, "push3.adr", sIN_CSEG, parm3 }, /* version 9 */ - {142, "push3.c", sIN_CSEG, parm3 }, /* version 9 */ - {144, "push3.s", sIN_CSEG, parm3 }, /* version 9 */ - {147, "push4", sIN_CSEG, parm4 }, /* version 9 */ - {149, "push4.adr", sIN_CSEG, parm4 }, /* version 9 */ - {146, "push4.c", sIN_CSEG, parm4 }, /* version 9 */ - {148, "push4.s", sIN_CSEG, parm4 }, /* version 9 */ - {151, "push5", sIN_CSEG, parm5 }, /* version 9 */ - {153, "push5.adr", sIN_CSEG, parm5 }, /* version 9 */ - {150, "push5.c", sIN_CSEG, parm5 }, /* version 9 */ - {152, "push5.s", sIN_CSEG, parm5 }, /* version 9 */ - { 47, "ret", sIN_CSEG, parm0 }, - { 48, "retn", sIN_CSEG, parm0 }, - { 32, "sctrl", sIN_CSEG, parm1 }, - { 73, "sdiv", sIN_CSEG, parm0 }, - { 74, "sdiv.alt", sIN_CSEG, parm0 }, - {104, "sgeq", sIN_CSEG, parm0 }, - {103, "sgrtr", sIN_CSEG, parm0 }, - { 65, "shl", sIN_CSEG, parm0 }, - { 69, "shl.c.alt", sIN_CSEG, parm1 }, - { 68, "shl.c.pri", sIN_CSEG, parm1 }, - { 66, "shr", sIN_CSEG, parm0 }, - { 71, "shr.c.alt", sIN_CSEG, parm1 }, - { 70, "shr.c.pri", sIN_CSEG, parm1 }, - { 94, "sign.alt", sIN_CSEG, parm0 }, - { 93, "sign.pri", sIN_CSEG, parm0 }, - {102, "sleq", sIN_CSEG, parm0 }, - {101, "sless", sIN_CSEG, parm0 }, - { 72, "smul", sIN_CSEG, parm0 }, - { 88, "smul.c", sIN_CSEG, parm1 }, -/*{127, "srange", sIN_CSEG, parm2 }, -- version 1 */ - { 20, "sref.alt", sIN_CSEG, parm1 }, - { 19, "sref.pri", sIN_CSEG, parm1 }, - { 22, "sref.s.alt", sIN_CSEG, parm1 }, - { 21, "sref.s.pri", sIN_CSEG, parm1 }, - { 67, "sshr", sIN_CSEG, parm0 }, - { 44, "stack", sIN_CSEG, parm1 }, - {165, "stackadjust",sIN_CSEG, parm1 }, - { 0, "stksize", 0, noop }, - { 16, "stor.alt", sIN_CSEG, parm1 }, - { 23, "stor.i", sIN_CSEG, parm0 }, - { 15, "stor.pri", sIN_CSEG, parm1 }, - { 18, "stor.s.alt", sIN_CSEG, parm1 }, - { 17, "stor.s.pri", sIN_CSEG, parm1 }, - {164, "stradjust.pri", sIN_CSEG, parm0 }, - { 24, "strb.i", sIN_CSEG, parm1 }, - { 79, "sub", sIN_CSEG, parm0 }, - { 80, "sub.alt", sIN_CSEG, parm0 }, - {132, "swap.alt", sIN_CSEG, parm0 }, /* version 4 */ - {131, "swap.pri", sIN_CSEG, parm0 }, /* version 4 */ - {129, "switch", sIN_CSEG, do_switch }, /* version 1 */ -/*{126, "symbol", sIN_CSEG, do_symbol }, */ -/*{136, "symtag", sIN_CSEG, parm1 }, -- version 7 */ - {123, "sysreq.c", sIN_CSEG, parm1 }, - {135, "sysreq.n", sIN_CSEG, parm2 }, /* version 9 (replaces SYSREQ.d from earlier version) */ - {122, "sysreq.pri", sIN_CSEG, parm0 }, - {161, "tracker.pop.setheap", sIN_CSEG, parm0 }, - {160, "tracker.push.c", sIN_CSEG, parm1 }, - { 76, "udiv", sIN_CSEG, parm0 }, - { 77, "udiv.alt", sIN_CSEG, parm0 }, - { 75, "umul", sIN_CSEG, parm0 }, - { 35, "xchg", sIN_CSEG, parm0 }, - { 83, "xor", sIN_CSEG, parm0 }, - { 91, "zero", sIN_CSEG, parm1 }, - { 90, "zero.alt", sIN_CSEG, parm0 }, - { 89, "zero.pri", sIN_CSEG, parm0 }, - { 92, "zero.s", sIN_CSEG, parm1 }, -}; - -#define MAX_INSTR_LEN 30 -static int findopcode(char *instr,int maxlen) -{ - int low,high,mid,cmp; - char str[MAX_INSTR_LEN]; - - if (maxlen>=MAX_INSTR_LEN) - return 0; - strlcpy(str,instr,maxlen+1); - /* look up the instruction with a binary search - * the assembler is case insensitive to instructions (but case sensitive - * to symbols) - */ - low=1; /* entry 0 is reserved (for "not found") */ - high=(sizeof opcodelist / sizeof opcodelist[0])-1; - while (low0) - low=mid+1; - else - high=mid; - } /* while */ - - assert(low==high); - if (stricmp(str,opcodelist[low].name)==0) - return low; /* found */ - return 0; /* not found, return special index */ -} - -// This pass is necessary because the code addresses of labels is only known -// after the peephole optimization flag. Labels can occur inside expressions -// (e.g. the conditional operator), which are optimized. -static void relocate_labels(void *fin) -{ - if (sc_labnum <= 0) - return; - - assert(!LabelTable); - LabelTable = (cell *)calloc(sc_labnum, sizeof(cell)); - - char line[256]; - cell codeindex = 0; - - pc_resetasm(fin); - while (pc_readasm(fin, line, sizeof(line))) { - stripcomment(line); - - char *instr = skipwhitespace(line); - if (*instr == '\0') // Ignore empty lines. - continue; - - if (tolower(*instr) == 'l' && *(instr + 1) == '.') { - int lindex = (int)hex2long(instr + 2, nullptr); - assert(lindex >= 0 && lindex < sc_labnum); - LabelTable[lindex] = codeindex; - } else { - // Get to the end of the instruction (make use of the '\n' that fgets() - // added at the end of the line; this way we *always* drop on a whitespace - // character. - char *params; - for (params = instr; *params != '\0' && !isspace(*params); params++) { - // Nothing. - } - assert(params > instr); - - int op_index = findopcode(instr, (int)(params - instr)); - OPCODEC &op = opcodelist[op_index]; - if (!op.name) { - *params = '\0'; - error(104, instr); - } - - if (op.segment == sIN_CSEG) - codeindex += op.func(nullptr, skipwhitespace(params), op.opcode); - } - } -} - -// Generate code or data into a buffer. -static void generate_segment(Vector *buffer, void *fin, int pass) -{ - pc_resetasm(fin); - - char line[255]; - while (pc_readasm(fin, line, sizeof(line))) { - stripcomment(line); - char *instr = skipwhitespace(line); - - // Ignore empty lines and labels. - if (*instr=='\0' || (tolower(*instr) == 'l' && *(instr + 1)=='.')) - continue; - - // Get to the end of the instruction (make use of the '\n' that fgets() - // added at the end of the line; this way we will *always* drop on a - // whitespace character) */ - char *params; - for (params=instr; *params != '\0' && !isspace(*params); params++) { - // Do nothing. - } - assert(params > instr); - - int op_index = findopcode(instr, (int)(params-instr)); - OPCODEC &op = opcodelist[op_index]; - assert(op.name != nullptr); - - if (op.segment != pass) - continue; - - op.func(buffer, skipwhitespace(params), op.opcode); - } -} - -#if !defined NDEBUG -// The opcode list should be sorted by name. -class VerifyOpcodeSorting -{ - public: - VerifyOpcodeSorting() { - assert(opcodelist[1].name!=NULL); - for (size_t i = 2; i<(sizeof opcodelist / sizeof opcodelist[0]); i++) { - assert(opcodelist[i].name!=NULL); - assert(stricmp(opcodelist[i].name,opcodelist[i-1].name)>0); - } /* for */ - } -} sVerifyOpcodeSorting; -#endif - -static int sort_by_addr(const void *a1, const void *a2) -{ - symbol *s1 = *(symbol **)a1; - symbol *s2 = *(symbol **)a2; - return s1->addr - s2->addr; -} - -struct function_entry { - symbol *sym; - AString name; -}; - -static int sort_functions(const void *a1, const void *a2) -{ - function_entry &f1 = *(function_entry *)a1; - function_entry &f2 = *(function_entry *)a2; - return strcmp(f1.name.chars(), f2.name.chars()); -} - -// Helper for parsing a debug string. Debug strings look like this: -// L:40 10 -class DebugString -{ - public: - DebugString() : kind_('\0'), str_(nullptr) - { } - DebugString(char *str) - : kind_(str[0]), - str_(str) - { - assert(str_[1] == ':'); - str_ += 2; - } - char kind() const { - return kind_; - } - ucell parse() { - return hex2long(str_, &str_); - } - char *skipspaces() { - str_ = ::skipwhitespace(str_); - return str_; - } - void expect(char c) { - assert(*str_ == c); - str_++; - } - char *skipto(char c) { - str_ = strchr(str_, c); - return str_; - } - char getc() { - return *str_++; - } - - private: - char kind_; - char *str_; -}; - -typedef SmxBlobSection SmxDebugInfoSection; -typedef SmxListSection SmxDebugLineSection; -typedef SmxListSection SmxDebugFileSection; -typedef SmxListSection SmxTagSection; -typedef SmxBlobSection SmxDebugSymbolsSection; -typedef SmxBlobSection SmxDebugNativesSection; -typedef Vector SymbolList; - -static void append_debug_tables(SmxBuilder *builder, StringPool &pool, Ref names, SymbolList &nativeList) -{ - // We use a separate name table for historical reasons that are no longer - // necessary. In the future we should just alias this to ".names". - Ref dbgnames = new SmxNameTable(".dbg.strings"); - Ref info = new SmxDebugInfoSection(".dbg.info"); - Ref lines = new SmxDebugLineSection(".dbg.lines"); - Ref files = new SmxDebugFileSection(".dbg.files"); - Ref symbols = new SmxDebugSymbolsSection(".dbg.symbols"); - Ref natives = new SmxDebugNativesSection(".dbg.natives"); - Ref tags = new SmxTagSection(".tags"); - - stringlist *dbgstrs = get_dbgstrings(); - - // State for tracking which file we're on. We replicate the original AMXDBG - // behavior here which excludes duplicate addresses. - ucell prev_file_addr = 0; - const char *prev_file_name = nullptr; - - // Add debug data. - for (stringlist *iter = dbgstrs; iter; iter = iter->next) { - if (iter->line[0] == '\0') - continue; - - DebugString str(iter->line); - switch (str.kind()) { - case 'F': - { - ucell codeidx = str.parse(); - if (codeidx != prev_file_addr) { - if (prev_file_name) { - sp_fdbg_file_t &entry = files->add(); - entry.addr = prev_file_addr; - entry.name = dbgnames->add(pool, prev_file_name); - } - prev_file_addr = codeidx; - } - prev_file_name = str.skipspaces(); - break; - } - - case 'L': - { - sp_fdbg_line_t &entry = lines->add(); - entry.addr = str.parse(); - entry.line = str.parse(); - break; - } - - case 'S': - { - sp_fdbg_symbol_t sym; - sp_fdbg_arraydim_t dims[sDIMEN_MAX]; - - sym.addr = str.parse(); - sym.tagid = str.parse(); - - str.skipspaces(); - str.expect(':'); - char *name = str.skipspaces(); - char *nameend = str.skipto(' '); - Atom *atom = pool.add(name, nameend - name); - - sym.codestart = str.parse(); - sym.codeend = str.parse(); - sym.ident = (char)str.parse(); - sym.vclass = (char)str.parse(); - sym.dimcount = 0; - sym.name = dbgnames->add(atom); - - info->header().num_syms++; - - str.skipspaces(); - if (str.getc() == '[') { - info->header().num_arrays++; - for (char *ptr = str.skipspaces(); *ptr != ']'; ptr = str.skipspaces()) { - dims[sym.dimcount].tagid = str.parse(); - str.skipspaces(); - str.expect(':'); - dims[sym.dimcount].size = str.parse(); - sym.dimcount++; - } - } - - symbols->add(&sym, sizeof(sym)); - symbols->add(dims, sizeof(dims[0]) * sym.dimcount); - break; - } - } - } - - // Add the last file. - if (prev_file_name) { - sp_fdbg_file_t &entry = files->add(); - entry.addr = prev_file_addr; - entry.name = dbgnames->add(pool, prev_file_name); - } - - // Build the tags table. - for (constvalue *constptr = tagname_tab.next; constptr; constptr = constptr->next) { - assert(strlen(constptr->name)>0); - - sp_file_tag_t &tag = tags->add(); - tag.tag_id = constptr->value; - tag.name = names->add(pool, constptr->name); - } - - // Finish up debug header statistics. - info->header().num_files = files->count(); - info->header().num_lines = lines->count(); - - // Write natives. - sp_fdbg_ntvtab_t natives_header; - natives_header.num_entries = nativeList.length(); - natives->add(&natives_header, sizeof(natives_header)); - - for (size_t i = 0; i < nativeList.length(); i++) { - symbol *sym = nativeList[i]; - - sp_fdbg_native_t info; - info.index = i; - info.name = dbgnames->add(pool, sym->name); - info.tagid = sym->tag; - info.nargs = 0; - for (arginfo *arg = sym->dim.arglist; arg->ident; arg++) - info.nargs++; - natives->add(&info, sizeof(info)); - - for (arginfo *arg = sym->dim.arglist; arg->ident; arg++) { - sp_fdbg_ntvarg_t argout; - argout.ident = arg->ident; - argout.tagid = arg->tags[0]; - argout.dimcount = arg->numdim; - argout.name = dbgnames->add(pool, arg->name); - natives->add(&argout, sizeof(argout)); - - for (int j = 0; j < argout.dimcount; j++) { - sp_fdbg_arraydim_t dim; - dim.tagid = arg->idxtag[j]; - dim.size = arg->dim[j]; - natives->add(&dim, sizeof(dim)); - } - } - } - - // Add these in the same order SourceMod 1.6 added them. - builder->add(files); - builder->add(symbols); - builder->add(lines); - builder->add(natives); - builder->add(dbgnames); - builder->add(info); - builder->add(tags); -} - -typedef SmxListSection SmxNativeSection; -typedef SmxListSection SmxPublicSection; -typedef SmxListSection SmxPubvarSection; -typedef SmxBlobSection SmxDataSection; -typedef SmxBlobSection SmxCodeSection; - -static void assemble_to_buffer(MemoryBuffer *buffer, void *fin) -{ - StringPool pool; - SmxBuilder builder; - Ref natives = new SmxNativeSection(".natives"); - Ref publics = new SmxPublicSection(".publics"); - Ref pubvars = new SmxPubvarSection(".pubvars"); - Ref data = new SmxDataSection(".data"); - Ref code = new SmxCodeSection(".code"); - Ref names = new SmxNameTable(".names"); - - Vector nativeList; - Vector functions; - - // Build the easy symbol tables. - for (symbol *sym=glbtab.next; sym; sym=sym->next) { - if (sym->ident==iFUNCTN) { - if ((sym->usage & uNATIVE)!=0 && (sym->usage & uREAD)!=0 && sym->addr >= 0) { - // Natives require special handling, so we save them for later. - nativeList.append(sym); - continue; - } - - if ((sym->usage & (uPUBLIC|uDEFINE)) == (uPUBLIC|uDEFINE) || - (sym->usage & uREAD)) - { - function_entry entry; - entry.sym = sym; - if (sym->usage & uPUBLIC) { - entry.name = sym->name; - } else { - // Create a private name. - char private_name[sNAMEMAX*3 + 1]; - snprintf(private_name, sizeof(private_name), ".%d.%s", sym->addr, sym->name); - - entry.name = private_name; - } - - functions.append(entry); - continue; - } - } else if (sym->ident==iVARIABLE || sym->ident == iARRAY || sym->ident == iREFARRAY) { - if ((sym->usage & uPUBLIC)!=0 && (sym->usage & (uREAD | uWRITTEN))!=0) { - sp_file_pubvars_t &pubvar = pubvars->add(); - pubvar.address = sym->addr; - pubvar.name = names->add(pool, sym->name); - } - } - } - - // The public list must be sorted. - qsort(functions.buffer(), functions.length(), sizeof(function_entry), sort_functions); - for (size_t i = 0; i < functions.length(); i++) { - function_entry &f = functions[i]; - symbol *sym = f.sym; - - assert(sym->addr > 0); - assert(sym->codeaddr > sym->addr); - assert(sym->usage & uDEFINE); - - sp_file_publics_t &pubfunc = publics->add(); - pubfunc.address = sym->addr; - pubfunc.name = names->add(pool, f.name.chars()); - - sym->funcid = (uint32_t(i) << 1) | 1; - } - - // Shuffle natives to be in address order. - qsort(nativeList.buffer(), nativeList.length(), sizeof(symbol *), sort_by_addr); - for (size_t i = 0; i < nativeList.length(); i++) { - symbol *sym = nativeList[i]; - assert(size_t(sym->addr) == i); - - sp_file_natives_t &entry = natives->add(); - - char testalias[sNAMEMAX + 1]; - if (lookup_alias(testalias, sym->name)) - entry.name = names->add(pool, "@"); - else - entry.name = names->add(pool, sym->name); - } - - // Relocate all labels in the assembly buffer. - relocate_labels(fin); - - // Generate buffers. - Vector code_buffer, data_buffer; - generate_segment(&code_buffer, fin, sIN_CSEG); - generate_segment(&data_buffer, fin, sIN_DSEG); - - // Set up the code section. - code->header().codesize = code_buffer.length() * sizeof(cell); - code->header().cellsize = sizeof(cell); - code->header().codeversion = SmxConsts::CODE_VERSION_JIT_1_1; - code->header().flags = CODEFLAG_DEBUG; - code->header().main = 0; - code->header().code = sizeof(sp_file_code_t); - code->setBlob((uint8_t *)code_buffer.buffer(), code_buffer.length() * sizeof(cell)); - - // Set up the data section. Note pre-SourceMod 1.7, the |memsize| was - // computed as AMX::stp, which included the entire memory size needed to - // store the file. Here (in 1.7+), we allocate what is actually needed - // by the plugin. - data->header().datasize = data_buffer.length() * sizeof(cell); - data->header().memsize = - data->header().datasize + - glb_declared * sizeof(cell) + - pc_stksize * sizeof(cell); - data->header().data = sizeof(sp_file_data_t); - data->setBlob((uint8_t *)data_buffer.buffer(), data_buffer.length() * sizeof(cell)); - - free(LabelTable); - LabelTable = nullptr; - - // Add tables in the same order SourceMod 1.6 added them. - builder.add(code); - builder.add(data); - builder.add(publics); - builder.add(pubvars); - builder.add(natives); - builder.add(names); - append_debug_tables(&builder, pool, names, nativeList); - - builder.write(buffer); -} - -static void splat_to_binary(const char *binfname, void *bytes, size_t size) -{ - // Note: error 161 will setjmp(), which skips destructors :( - FILE *fp = fopen(binfname, "wb"); - if (!fp) { - error(FATAL_ERROR_WRITE, binfname); - return; - } - if (fwrite(bytes, 1, size, fp) != size) { - fclose(fp); - error(FATAL_ERROR_WRITE, binfname); - return; - } - fclose(fp); -} - -void assemble(const char *binfname, void *fin) -{ - MemoryBuffer buffer; - assemble_to_buffer(&buffer, fin); - - // Buffer compression logic. - sp_file_hdr_t *header = (sp_file_hdr_t *)buffer.bytes(); - size_t region_size = header->imagesize - header->dataoffs; - size_t zbuf_max = compressBound(region_size); - Bytef *zbuf = (Bytef *)malloc(zbuf_max); - - uLong new_disksize = zbuf_max; - int err = compress2( - zbuf, - &new_disksize, - (Bytef *)(buffer.bytes() + header->dataoffs), - region_size, - Z_BEST_COMPRESSION - ); - if (err != Z_OK) { - free(zbuf); - pc_printf("Unable to compress, error %d\n", err); - pc_printf("Falling back to no compression.\n"); - splat_to_binary(binfname, buffer.bytes(), buffer.size()); - return; - } - - header->disksize = new_disksize + header->dataoffs; - header->compression = SmxConsts::FILE_COMPRESSION_GZ; - - buffer.rewind(header->dataoffs); - buffer.write(zbuf, new_disksize); - free(zbuf); - - splat_to_binary(binfname, buffer.bytes(), buffer.size()); -} diff --git a/sourcepawn/compiler/sc7-in.scp b/sourcepawn/compiler/sc7-in.scp deleted file mode 100644 index 3f7c3e34..00000000 --- a/sourcepawn/compiler/sc7-in.scp +++ /dev/null @@ -1,1218 +0,0 @@ -/* Pawn compiler - Peephole optimizer "sequences" strings (plain - * and compressed formats) - * - * Copyright (c) ITB CompuPhase, 2000-2006 - * - * This software is provided "as-is", without any express or implied warranty. - * In no event will the authors be held liable for any damages arising from - * the use of this software. - * - * Permission is granted to anyone to use this software for any purpose, - * including commercial applications, and to alter it and redistribute it - * freely, subject to the following restrictions: - * - * 1. The origin of this software must not be misrepresented; you must not - * claim that you wrote the original software. If you use this software in - * a product, an acknowledgment in the product documentation would be - * appreciated but is not required. - * 2. Altered source versions must be plainly marked as such, and must not be - * misrepresented as being the original software. - * 3. This notice may not be removed or altered from any source distribution. - * - * Version: $Id$ - */ - -#define SCPACK_TERMINATOR , /* end each section with a comma */ - -#define SCPACK_TABLE sequences_table - -#define seqsize(o,p) (opcodes(o)+opargs(p)) -typedef struct { - const char *find; - const char *replace; - int savesize; /* number of bytes saved (in bytecode) */ -} SEQUENCE; -static SEQUENCE sequences_cmp[] = { - /* A very common sequence in four varieties - * load.s.pri n1 load.s.pri n2 - * push.pri load.s.alt n1 - * load.s.pri n2 - - * pop.alt - - * -------------------------------------- - * load.pri n1 load.s.pri n2 - * push.pri load.alt n1 - * load.s.pri n2 - - * pop.alt - - * -------------------------------------- - * load.s.pri n1 load.pri n2 - * push.pri load.s.alt n1 - * load.pri n2 - - * pop.alt - - * -------------------------------------- - * load.pri n1 load.pri n2 - * push.pri load.alt n1 - * load.pri n2 - - * pop.alt - - */ - { - "load.s.pri %1!push.pri!load.s.pri %2!pop.alt!", - "load.s.pri %2!load.s.alt %1!", - seqsize(4,2) - seqsize(2,2) - }, - { - "load.pri %1!push.pri!load.s.pri %2!pop.alt!", - "load.s.pri %2!load.alt %1!", - seqsize(4,2) - seqsize(2,2) - }, - { - "load.s.pri %1!push.pri!load.pri %2!pop.alt!", - "load.pri %2!load.s.alt %1!", - seqsize(4,2) - seqsize(2,2) - }, - { - "load.pri %1!push.pri!load.pri %2!pop.alt!", - "load.pri %2!load.alt %1!", - seqsize(4,2) - seqsize(2,2) - }, - /* (#1#) The above also occurs with "addr.pri" (array - * indexing) as the first line; so that adds 2 cases. - */ - { - "addr.pri %1!push.pri!load.s.pri %2!pop.alt!", - "addr.alt %1!load.s.pri %2!", - seqsize(4,2) - seqsize(2,2) - }, - { - "addr.pri %1!push.pri!load.pri %2!pop.alt!", - "addr.alt %1!load.pri %2!", - seqsize(4,2) - seqsize(2,2) - }, - /* And the same sequence with const.pri as either the first - * or the second load instruction: four more cases. - */ - { - "const.pri %1!push.pri!load.s.pri %2!pop.alt!", - "load.s.pri %2!const.alt %1!", - seqsize(4,2) - seqsize(2,2) - }, - { - "const.pri %1!push.pri!load.pri %2!pop.alt!", - "load.pri %2!const.alt %1!", - seqsize(4,2) - seqsize(2,2) - }, - { - "load.s.pri %1!push.pri!const.pri %2!pop.alt!", - "const.pri %2!load.s.alt %1!", - seqsize(4,2) - seqsize(2,2) - }, - { - "load.pri %1!push.pri!const.pri %2!pop.alt!", - "const.pri %2!load.alt %1!", - seqsize(4,2) - seqsize(2,2) - }, - /* The same as above, but now with "addr.pri" (array - * indexing) on the first line and const.pri on - * the second. - */ - { - "addr.pri %1!push.pri!const.pri %2!pop.alt!", - "addr.alt %1!const.pri %2!", - seqsize(4,2) - seqsize(2,2) - }, - { - "addr.pri %1!push.pri!zero.pri!pop.alt!", - "addr.alt %1!zero.pri!", - seqsize(4,1) - seqsize(2,1) - }, - /* ??? add references */ - /* Chained relational operators can contain sequences like: - * move.pri load.s.pri n1 - * push.pri - - * load.s.pri n1 - - * pop.alt - - * The above also accurs for "load.pri" and for "const.pri", - * so add another two cases. - */ - { - "move.pri!push.pri!load.s.pri %1!pop.alt!", - "load.s.pri %1!", - seqsize(4,1) - seqsize(1,1) - }, - { - "move.pri!push.pri!load.pri %1!pop.alt!", - "load.pri %1!", - seqsize(4,1) - seqsize(1,1) - }, - { - "move.pri!push.pri!const.pri %1!pop.alt!", - "const.pri %1!", - seqsize(4,1) - seqsize(1,1) - }, - /* More optimizations for chained relational operators; the - * continuation sequences can be simplified if they turn out - * to be termination sequences: - * xchg sless also for sless, sgeq and sleq - * sgrtr pop.alt - * swap.alt and - * and ;$exp - * pop.alt - - * ;$exp - - * -------------------------------------- - * xchg sless also for sless, sgeq and sleq - * sgrtr pop.alt - * swap.alt and - * and jzer n1 - * pop.alt - - * jzer n1 - - * -------------------------------------- - * xchg jsgeq n1 also for sless, sgeq and sleq - * sgrtr ;$exp (occurs for non-chained comparisons) - * jzer n1 - - * ;$exp - - * -------------------------------------- - * xchg sless also for sless, sgeq and sleq - * sgrtr ;$exp (occurs for non-chained comparisons) - * ;$exp - - */ - { - "xchg!sgrtr!swap.alt!and!pop.alt!;$exp!", - "sless!pop.alt!and!;$exp!", - seqsize(5,0) - seqsize(3,0) - }, - { - "xchg!sless!swap.alt!and!pop.alt!;$exp!", - "sgrtr!pop.alt!and!;$exp!", - seqsize(5,0) - seqsize(3,0) - }, - { - "xchg!sgeq!swap.alt!and!pop.alt!;$exp!", - "sleq!pop.alt!and!;$exp!", - seqsize(5,0) - seqsize(3,0) - }, - { - "xchg!sleq!swap.alt!and!pop.alt!;$exp!", - "sgeq!pop.alt!and!;$exp!", - seqsize(5,0) - seqsize(3,0) - }, - { - "xchg!sgrtr!swap.alt!and!pop.alt!jzer %1!", - "sless!pop.alt!and!jzer %1!", - seqsize(5,0) - seqsize(3,0) - }, - { - "xchg!sless!swap.alt!and!pop.alt!jzer %1!", - "sgrtr!pop.alt!and!jzer %1!", - seqsize(5,0) - seqsize(3,0) - }, - { - "xchg!sgeq!swap.alt!and!pop.alt!jzer %1!", - "sleq!pop.alt!and!jzer %1!", - seqsize(5,0) - seqsize(3,0) - }, - { - "xchg!sleq!swap.alt!and!pop.alt!jzer %1!", - "sgeq!pop.alt!and!jzer %1!", - seqsize(5,0) - seqsize(3,0) - }, - { - "xchg!sgrtr!jzer %1!;$exp!", - "jsgeq %1!;$exp!", - seqsize(3,1) - seqsize(1,1) - }, - { - "xchg!sless!jzer %1!;$exp!", - "jsleq %1!;$exp!", - seqsize(3,1) - seqsize(1,1) - }, - { - "xchg!sgeq!jzer %1!;$exp!", - "jsgrtr %1!;$exp!", - seqsize(3,1) - seqsize(1,1) - }, - { - "xchg!sleq!jzer %1!;$exp!", - "jsless %1!;$exp!", - seqsize(3,1) - seqsize(1,1) - }, - { - "xchg!sgrtr!;$exp!", - "sless!;$exp!", - seqsize(2,0) - seqsize(1,0) - }, - { - "xchg!sless!;$exp!", - "sgrtr!;$exp!", - seqsize(2,0) - seqsize(1,0) - }, - { - "xchg!sgeq!;$exp!", - "sleq!;$exp!", - seqsize(2,0) - seqsize(1,0) - }, - { - "xchg!sleq!;$exp!", - "sgeq!;$exp!", - seqsize(2,0) - seqsize(1,0) - }, - /* The entry to chained operators is also opt to optimization - * load.s.pri n1 load.s.pri n2 - * load.s.alt n2 load.s.alt n1 - * xchg - - * -------------------------------------- - * load.s.pri n1 load.pri n2 - * load.alt n2 load.s.alt n1 - * xchg - - * -------------------------------------- - * load.s.pri n1 const.pri n2 - * const.alt n2 load.s.alt n1 - * xchg - - * -------------------------------------- - * and all permutations... - */ - { - "load.s.pri %1!load.s.alt %2!xchg!", - "load.s.pri %2!load.s.alt %1!", - seqsize(3,2) - seqsize(2,2) - }, - { - "load.s.pri %1!load.alt %2!xchg!", - "load.pri %2!load.s.alt %1!", - seqsize(3,2) - seqsize(2,2) - }, - { - "load.s.pri %1!const.alt %2!xchg!", - "const.pri %2!load.s.alt %1!", - seqsize(3,2) - seqsize(2,2) - }, - { - "load.pri %1!load.s.alt %2!xchg!", - "load.s.pri %2!load.alt %1!", - seqsize(3,2) - seqsize(2,2) - }, - { - "load.pri %1!load.alt %2!xchg!", - "load.pri %2!load.alt %1!", - seqsize(3,2) - seqsize(2,2) - }, - { - "load.pri %1!const.alt %2!xchg!", - "const.pri %2!load.alt %1!", - seqsize(3,2) - seqsize(2,2) - }, - { - "const.pri %1!load.s.alt %2!xchg!", - "load.s.pri %2!const.alt %1!", - seqsize(3,2) - seqsize(2,2) - }, - { - "const.pri %1!load.alt %2!xchg!", - "load.pri %2!const.alt %1!", - seqsize(3,2) - seqsize(2,2) - }, - /* some sequences where PRI is moved to ALT can be optimized - * further when considering what follows - * move.alt const.alt n1 - * const.pri %1 - - * xchg - - * (also for load.s.pri and load.pri) - * -------------------------------------- - * lref.pri %1 lref.alt %1 - * move.alt [load.pri %2] - * [load.pri %2] - - * (where [load.pri %2] may also be another operatrion loading PRI) - */ - { - "move.alt!const.pri %1!xchg!", - "const.alt %1!", - seqsize(3,1) - seqsize(1,1) - }, - { - "move.alt!load.pri %1!xchg!", - "load.alt %1!", - seqsize(3,1) - seqsize(1,1) - }, - { - "move.alt!load.s.pri %1!xchg!", - "load.s.alt %1!", - seqsize(3,1) - seqsize(1,1) - }, - /* ----- */ - { - "lref.pri %1!move.alt!load.pri %2!", - "lref.alt %1!load.pri %2!", - seqsize(3,2) - seqsize(2,2) - }, - { - "lref.pri %1!move.alt!load.s.pri %2!", - "lref.alt %1!load.s.pri %2!", - seqsize(3,2) - seqsize(2,2) - }, - { - "lref.pri %1!move.alt!const.pri %2!", - "lref.alt %1!const.pri %2!", - seqsize(3,2) - seqsize(2,2) - }, - { - "lref.s.pri %1!move.alt!load.pri %2!", - "lref.s.alt %1!load.pri %2!", - seqsize(3,2) - seqsize(2,2) - }, - { - "lref.s.pri %1!move.alt!load.s.pri %2!", - "lref.s.alt %1!load.s.pri %2!", - seqsize(3,2) - seqsize(2,2) - }, - { - "lref.s.pri %1!move.alt!const.pri %2!", - "lref.s.alt %1!const.pri %2!", - seqsize(3,2) - seqsize(2,2) - }, - /* Array indexing can merit from special instructions. - * Simple indexed array lookup can be optimized quite - * a bit. - * addr.pri n1 addr.alt n1 - * push.pri load.s.pri n2 - * load.s.pri n2 bounds n3 - * bounds n3 lidx.b n4 - * shl.c.pri n4 - - * pop.alt - - * add - - * load.i - - * - * And to prepare for storing a value in an array - * addr.pri n1 addr.alt n1 - * push.pri load.s.pri n2 - * load.s.pri n2 bounds n3 - * bounds n3 idxaddr.b n4 - * shl.c.pri n4 - - * pop.alt - - * add - - * - * Notes (additional cases): - * 1. instruction addr.pri can also be const.pri (for - * global arrays) - * 2. the bounds instruction can be absent - * 3. when "n4" (the shift value) is the 2 (with 32-bit cells), use the - * even more optimal instructions LIDX and IDDXADDR - * - * If the array index is more complex, one can only optimize - * the last four instructions: - * shl.c.pri n1 pop.alt - * pop.alt lidx.b n1 - * add - - * loadi - - * -------------------------------------- - * shl.c.pri n1 pop.alt - * pop.alt idxaddr.b n1 - * add - - */ -#if !defined BIT16 - /* loading from array, "cell" shifted */ - { - "addr.pri %1!push.pri!load.s.pri %2!bounds %3!shl.c.pri 2!pop.alt!add!load.i!", - "addr.alt %1!load.s.pri %2!bounds %3!lidx!", - seqsize(8,4) - seqsize(4,3) - }, - { - "const.pri %1!push.pri!load.s.pri %2!bounds %3!shl.c.pri 2!pop.alt!add!load.i!", - "const.alt %1!load.s.pri %2!bounds %3!lidx!", - seqsize(8,4) - seqsize(4,3) - }, - { - "addr.pri %1!push.pri!load.s.pri %2!shl.c.pri 2!pop.alt!add!load.i!", - "addr.alt %1!load.s.pri %2!lidx!", - seqsize(7,3) - seqsize(3,2) - }, - { - "const.pri %1!push.pri!load.s.pri %2!shl.c.pri 2!pop.alt!add!load.i!", - "const.alt %1!load.s.pri %2!lidx!", - seqsize(7,3) - seqsize(3,2) - }, -#endif - /* loading from array, not "cell" shifted */ - { - "addr.pri %1!push.pri!load.s.pri %2!bounds %3!shl.c.pri %4!pop.alt!add!load.i!", - "addr.alt %1!load.s.pri %2!bounds %3!lidx.b %4!", - seqsize(8,4) - seqsize(4,4) - }, - { - "const.pri %1!push.pri!load.s.pri %2!bounds %3!shl.c.pri %4!pop.alt!add!load.i!", - "const.alt %1!load.s.pri %2!bounds %3!lidx.b %4!", - seqsize(8,4) - seqsize(4,4) - }, - { - "addr.pri %1!push.pri!load.s.pri %2!shl.c.pri %3!pop.alt!add!load.i!", - "addr.alt %1!load.s.pri %2!lidx.b %3!", - seqsize(7,3) - seqsize(3,3) - }, - { - "const.pri %1!push.pri!load.s.pri %2!shl.c.pri %3!pop.alt!add!load.i!", - "const.alt %1!load.s.pri %2!lidx.b %3!", - seqsize(7,3) - seqsize(3,3) - }, -#if !defined BIT16 - /* array index calculation for storing a value, "cell" aligned */ - { - "addr.pri %1!push.pri!load.s.pri %2!bounds %3!shl.c.pri 2!pop.alt!add!", - "addr.alt %1!load.s.pri %2!bounds %3!idxaddr!", - seqsize(7,4) - seqsize(4,3) - }, - { - "const.pri %1!push.pri!load.s.pri %2!bounds %3!shl.c.pri 2!pop.alt!add!", - "const.alt %1!load.s.pri %2!bounds %3!idxaddr!", - seqsize(7,4) - seqsize(4,3) - }, - { - "addr.pri %1!push.pri!load.s.pri %2!shl.c.pri 2!pop.alt!add!", - "addr.alt %1!load.s.pri %2!idxaddr!", - seqsize(6,3) - seqsize(3,2) - }, - { - "const.pri %1!push.pri!load.s.pri %2!shl.c.pri 2!pop.alt!add!", - "const.alt %1!load.s.pri %2!idxaddr!", - seqsize(6,3) - seqsize(3,2) - }, -#endif - /* array index calculation for storing a value, not "cell" packed */ - { - "addr.pri %1!push.pri!load.s.pri %2!bounds %3!shl.c.pri %4!pop.alt!add!", - "addr.alt %1!load.s.pri %2!bounds %3!idxaddr.b %4!", - seqsize(7,4) - seqsize(4,4) - }, - { - "const.pri %1!push.pri!load.s.pri %2!bounds %3!shl.c.pri %4!pop.alt!add!", - "const.alt %1!load.s.pri %2!bounds %3!idxaddr.b %4!", - seqsize(7,4) - seqsize(4,4) - }, - { - "addr.pri %1!push.pri!load.s.pri %2!shl.c.pri %3!pop.alt!add!", - "addr.alt %1!load.s.pri %2!idxaddr.b %3!", - seqsize(6,3) - seqsize(3,3) - }, - { - "const.pri %1!push.pri!load.s.pri %2!shl.c.pri %3!pop.alt!add!", - "const.alt %1!load.s.pri %2!idxaddr.b %3!", - seqsize(6,3) - seqsize(3,3) - }, -#if !defined BIT16 - /* the shorter array indexing sequences, see above for comments */ - { - "shl.c.pri 2!pop.alt!add!loadi!", - "pop.alt!lidx!", - seqsize(4,1) - seqsize(2,0) - }, - { - "shl.c.pri 2!pop.alt!add!", - "pop.alt!idxaddr!", - seqsize(3,1) - seqsize(2,0) - }, -#endif - { - "shl.c.pri %1!pop.alt!add!loadi!", - "pop.alt!lidx.b %1!", - seqsize(4,1) - seqsize(2,1) - }, - { - "shl.c.pri %1!pop.alt!add!", - "pop.alt!idxaddr.b %1!", - seqsize(3,1) - seqsize(2,1) - }, - /* For packed arrays, there is another case (packed arrays - * do not take advantage of the LIDX or IDXADDR instructions). - * addr.pri n1 addr.alt n1 - * push.pri load.s.pri n2 - * load.s.pri n2 bounds n3 - * bounds n3 - - * pop.alt - - * - * Notes (additional cases): - * 1. instruction addr.pri can also be const.pri (for - * global arrays) - * 2. the bounds instruction can be absent, but that - * case is already handled (see #1#) - */ - { - "addr.pri %1!push.pri!load.s.pri %2!bounds %3!pop.alt!", - "addr.alt %1!load.s.pri %2!bounds %3!", - seqsize(5,3) - seqsize(3,3) - }, - { - "const.pri %1!push.pri!load.s.pri %2!bounds %3!pop.alt!", - "const.alt %1!load.s.pri %2!bounds %3!", - seqsize(5,3) - seqsize(3,3) - }, - /* Declaration of simple variables often follows the sequence: - * ;$lcl ;$lcl - * stack -4 push.c - * const.pri ;$exp - * stor.s.pri - - * ;$exp - - */ - { - ";$lcl %1 %2!stack -4!const.pri %3!stor.s.pri %2!;$exp!", - ";$lcl %1 %2!push.c %3!;$exp!", - seqsize(3,3) - seqsize(1,1) - }, - { - ";$lcl %1 %2!stack -4!zero.pri!stor.s.pri %2!;$exp!", - ";$lcl %1 %2!push.c 0!;$exp!", - seqsize(3,2) - seqsize(1,1) - }, - /* During a calculation, the intermediate result must sometimes - * be moved from PRI to ALT, like in: - * push.pri move.alt - * load.s.pri n1 load.s.pri n1 - * pop.alt - - * - * The above also accurs for "load.pri" and for "const.pri", - * so add another two cases. - */ - { - "push.pri!load.s.pri %1!pop.alt!", - "move.alt!load.s.pri %1!", - seqsize(3,1) - seqsize(2,1) - }, - { - "push.pri!load.pri %1!pop.alt!", - "move.alt!load.pri %1!", - seqsize(3,1) - seqsize(2,1) - }, - { - "push.pri!const.pri %1!pop.alt!", - "move.alt!const.pri %1!", - seqsize(3,1) - seqsize(2,1) - }, - { - "push.pri!zero.pri!pop.alt!", - "move.alt!zero.pri!", - seqsize(3,0) - seqsize(2,0) - }, - /* saving PRI and then loading from its address - * occurs when indexing a multi-dimensional array - */ - { - "push.pri!load.i!pop.alt!", - "move.alt!load.i!", - seqsize(3,0) - seqsize(2,0) - }, - /* An even simpler PUSH/POP optimization (occurs in - * switch statements): - * push.pri move.alt - * pop.alt - - */ - { - "push.pri!pop.alt!", - "move.alt!", - seqsize(2,0) - seqsize(1,0) - }, - /* Some simple arithmetic sequences - */ - { - "move.alt!load.s.pri %1!add!", - "load.s.alt %1!add!", - seqsize(3,1) - seqsize(2,1) - }, - { - "move.alt!load.pri %1!add!", - "load.alt %1!add!", - seqsize(3,1) - seqsize(2,1) - }, - { - "move.alt!const.pri %1!add!", - "const.alt %1!add!", - seqsize(3,1) - seqsize(2,1) - }, - { - "move.alt!load.s.pri %1!sub.alt!", - "load.s.alt %1!sub!", - seqsize(3,1) - seqsize(2,1) - }, - { - "move.alt!load.pri %1!sub.alt!", - "load.alt %1!sub!", - seqsize(3,1) - seqsize(2,1) - }, - { - "move.alt!const.pri %1!sub.alt!", - "const.alt %1!sub!", - seqsize(3,1) - seqsize(2,1) - }, - /* User-defined operators first load the operands into registers and - * then have them pushed onto the stack. This can give rise to sequences - * like: - * const.pri n1 push.c n1 - * const.alt n2 push.c n2 - * push.pri - - * push.alt - - * A similar sequence occurs with the two PUSH.pri/alt instructions inverted. - * The first, second, or both CONST.pri/alt instructions can also be - * LOAD.pri/alt. - * This gives 2 x 4 cases. - */ - { - "const.pri %1!const.alt %2!push.pri!push.alt!", - "push.c %1!push.c %2!", - seqsize(4,2) - seqsize(2,2) - }, - { - "const.pri %1!const.alt %2!push.alt!push.pri!", - "push.c %2!push.c %1!", - seqsize(4,2) - seqsize(2,2) - }, - { - "const.pri %1!load.alt %2!push.pri!push.alt!", - "push.c %1!push %2!", - seqsize(4,2) - seqsize(2,2) - }, - { - "const.pri %1!load.alt %2!push.alt!push.pri!", - "push %2!push.c %1!", - seqsize(4,2) - seqsize(2,2) - }, - { - "load.pri %1!const.alt %2!push.pri!push.alt!", - "push %1!push.c %2!", - seqsize(4,2) - seqsize(2,2) - }, - { - "load.pri %1!const.alt %2!push.alt!push.pri!", - "push.c %2!push %1!", - seqsize(4,2) - seqsize(2,2) - }, - { - "load.pri %1!load.alt %2!push.pri!push.alt!", - "push %1!push %2!", - seqsize(4,2) - seqsize(2,2) - }, - { - "load.pri %1!load.alt %2!push.alt!push.pri!", - "push %2!push %1!", - seqsize(4,2) - seqsize(2,2) - }, - /* Function calls (parameters are passed on the stack) - * load.s.pri n1 push.s n1 - * push.pri - - * -------------------------------------- - * load.pri n1 push n1 - * push.pri - - * -------------------------------------- - * const.pri n1 push.c n1 - * push.pri - - * -------------------------------------- - * zero.pri push.c 0 - * push.pri - - * -------------------------------------- - * addr.pri n1 push.adr n1 - * push.pri - - * - * However, PRI must not be needed after this instruction - * if this shortcut is used. Check for the ;$par comment. - */ - { - "load.s.pri %1!push.pri!;$par!", - "push.s %1!;$par!", - seqsize(2,1) - seqsize(1,1) - }, - { - "load.pri %1!push.pri!;$par!", - "push %1!;$par!", - seqsize(2,1) - seqsize(1,1) - }, - { - "const.pri %1!push.pri!;$par!", - "push.c %1!;$par!", - seqsize(2,1) - seqsize(1,1) - }, - { - "zero.pri!push.pri!;$par!", - "push.c 0!;$par!", - seqsize(2,0) - seqsize(1,1) - }, - { - "addr.pri %1!push.pri!;$par!", - "push.adr %1!;$par!", - seqsize(2,1) - seqsize(1,1) - }, - /* References with a default value generate new cells on the heap - * dynamically. That code often ends with: - * move.pri push.alt - * push.pri - - */ - { - "move.pri!push.pri!", - "push.alt!", - seqsize(2,0) - seqsize(1,0) - }, - /* Simple arithmetic operations on constants. Noteworthy is the - * subtraction of a constant, since it is converted to the addition - * of the inverse value. - * const.alt n1 add.c n1 - * add - - * -------------------------------------- - * const.alt n1 add.c -n1 - * sub - - * -------------------------------------- - * const.alt n1 smul.c n1 - * smul - - * -------------------------------------- - * const.alt n1 eq.c.pri n1 - * eq - - */ - { - "const.alt %1!add!", - "add.c %1!", - seqsize(2,1) - seqsize(1,1) - }, - { - "const.alt %1!sub!", - "add.c -%1!", - seqsize(2,1) - seqsize(1,1) - }, - { - "const.alt %1!smul!", - "smul.c %1!", - seqsize(2,1) - seqsize(1,1) - }, - { - "const.alt %1!eq!", - "eq.c.pri %1!", - seqsize(2,1) - seqsize(1,1) - }, - /* Some operations use the alternative subtraction operation --these - * can also be optimized. - * const.pri n1 load.s.pri n2 - * load.s.alt n2 add.c -n1 - * sub.alt - - * -------------------------------------- - * const.pri n1 load.pri n2 - * load.alt n2 add.c -n1 - * sub.alt - - */ - { - "const.pri %1!load.s.alt %2!sub.alt!", - "load.s.pri %2!add.c -%1!", - seqsize(3,2) - seqsize(2,2) - }, - { - "const.pri %1!load.alt %2!sub.alt!", - "load.pri %2!add.c -%1!", - seqsize(3,2) - seqsize(2,2) - }, - /* With arrays indexed with constants that come from enumerations, it happens - * multiple add.c opcodes follow in sequence. - * add.c n1 add.c n1+n2 - * add.c n2 - - */ - { - "add.c %1!add.c %2!", - "add.c %1+%2!", - seqsize(2,2) - seqsize(1,1) - }, - /* Compare and jump - * eq jneq n1 - * jzer n1 - - * -------------------------------------- - * eq jeq n1 - * jnz n1 - - * -------------------------------------- - * neq jeq n1 - * jzer n1 - - * -------------------------------------- - * neq jneq n1 - * jnz n1 - - * Compares followed by jzer occur much more - * often than compares followed with jnz. So we - * take the easy route here. - * less jgeq n1 - * jzer n1 - - * -------------------------------------- - * leq jgrtr n1 - * jzer n1 - - * -------------------------------------- - * grtr jleq n1 - * jzer n1 - - * -------------------------------------- - * geq jless n1 - * jzer n1 - - * -------------------------------------- - * sless jsgeq n1 - * jzer n1 - - * -------------------------------------- - * sleq jsgrtr n1 - * jzer n1 - - * -------------------------------------- - * sgrtr jsleq n1 - * jzer n1 - - * -------------------------------------- - * sgeq jsless n1 - * jzer n1 - - */ - { - "eq!jzer %1!", - "jneq %1!", - seqsize(2,1) - seqsize(1,1) - }, - { - "eq!jnz %1!", - "jeq %1!", - seqsize(2,1) - seqsize(1,1) - }, - { - "neq!jzer %1!", - "jeq %1!", - seqsize(2,1) - seqsize(1,1) - }, - { - "neq!jnz %1!", - "jneq %1!", - seqsize(2,1) - seqsize(1,1) - }, - { - "less!jzer %1!", - "jgeq %1!", - seqsize(2,1) - seqsize(1,1) - }, - { - "leq!jzer %1!", - "jgrtr %1!", - seqsize(2,1) - seqsize(1,1) - }, - { - "grtr!jzer %1!", - "jleq %1!", - seqsize(2,1) - seqsize(1,1) - }, - { - "geq!jzer %1!", - "jless %1!", - seqsize(2,1) - seqsize(1,1) - }, - { - "sless!jzer %1!", - "jsgeq %1!", - seqsize(2,1) - seqsize(1,1) - }, - { - "sleq!jzer %1!", - "jsgrtr %1!", - seqsize(2,1) - seqsize(1,1) - }, - { - "sgrtr!jzer %1!", - "jsleq %1!", - seqsize(2,1) - seqsize(1,1) - }, - { - "sgeq!jzer %1!", - "jsless %1!", - seqsize(2,1) - seqsize(1,1) - }, - /* Test for zero (common case, especially for strings) - * E.g. the test expression of: "for (i=0; str{i}!=0; ++i)" - * - * zero.alt jzer n1 - * jeq n1 - - * -------------------------------------- - * zero.alt jnz n1 - * jneq n1 - - */ - { - "zero.alt!jeq %1!", - "jzer %1!", - seqsize(2,1) - seqsize(1,1) - }, - { - "zero.alt!jneq %1!", - "jnz %1!", - seqsize(2,1) - seqsize(1,1) - }, - /* Incrementing and decrementing leaves a value in - * in PRI which may not be used (for example, as the - * third expression in a "for" loop). - * inc n1 inc n1 ; ++n - * load.pri n1 ;$exp - * ;$exp - - * -------------------------------------- - * load.pri n1 inc n1 ; n++, e.g. "for (n=0; n<10; n++)" - * inc n1 ;$exp - * ;$exp - - * Plus the varieties for stack relative increments - * and decrements. - */ - { - "inc %1!load.pri %1!;$exp!", - "inc %1!;$exp!", - seqsize(2,2) - seqsize(1,1) - }, - { - "load.pri %1!inc %1!;$exp!", - "inc %1!;$exp!", - seqsize(2,2) - seqsize(1,1) - }, - { - "inc.s %1!load.s.pri %1!;$exp!", - "inc.s %1!;$exp!", - seqsize(2,2) - seqsize(1,1) - }, - { - "load.s.pri %1!inc.s %1!;$exp!", - "inc.s %1!;$exp!", - seqsize(2,2) - seqsize(1,1) - }, - { - "dec %1!load.pri %1!;$exp!", - "dec %1!;$exp!", - seqsize(2,2) - seqsize(1,1) - }, - { - "load.pri %1!dec %1!;$exp!", - "dec %1!;$exp!", - seqsize(2,2) - seqsize(1,1) - }, - { - "dec.s %1!load.s.pri %1!;$exp!", - "dec.s %1!;$exp!", - seqsize(2,2) - seqsize(1,1) - }, - { - "load.s.pri %1!dec.s %1!;$exp!", - "dec.s %1!;$exp!", - seqsize(2,2) - seqsize(1,1) - }, - /* ??? the same (increments and decrements) for references */ - /* Loading the constant zero has a special opcode. - * When storing zero in memory, the value of PRI must not be later on. - * const.pri 0 zero n1 - * stor.pri n1 ;$exp - * ;$exp - - * -------------------------------------- - * const.pri 0 zero.s n1 - * stor.s.pri n1 ;$exp - * ;$exp - - * -------------------------------------- - * zero.pri zero n1 - * stor.pri n1 ;$exp - * ;$exp - - * -------------------------------------- - * zero.pri zero.s n1 - * stor.s.pri n1 ;$exp - * ;$exp - - * -------------------------------------- - * const.pri 0 zero.pri - * -------------------------------------- - * const.alt 0 zero.alt - * The last two alternatives save more memory than they save - * time, but anyway... - */ - { - "const.pri 0!stor.pri %1!;$exp!", - "zero %1!;$exp!", - seqsize(2,2) - seqsize(1,1) - }, - { - "const.pri 0!stor.s.pri %1!;$exp!", - "zero.s %1!;$exp!", - seqsize(2,2) - seqsize(1,1) - }, - { - "zero.pri!stor.pri %1!;$exp!", - "zero %1!;$exp!", - seqsize(2,1) - seqsize(1,1) - }, - { - "zero.pri!stor.s.pri %1!;$exp!", - "zero.s %1!;$exp!", - seqsize(2,1) - seqsize(1,1) - }, - { - "const.pri 0!", - "zero.pri!", - seqsize(1,1) - seqsize(1,0) - }, - { - "const.alt 0!", - "zero.alt!", - seqsize(1,1) - seqsize(1,0) - }, - - /* ------------------ */ - /* Macro instructions */ - /* ------------------ */ - - { "", "", 0 }, /* separator, so optimizer can stop before generating macro opcodes */ - - /* optimizing the calling of native functions (which always have a parameter - * count pushed before, and the stack pointer restored afterwards - */ - { - "push.c %1!sysreq.c %2!stack %3!", //note: %3 == %1 + 4 - "sysreq.n %2 %1!", - seqsize(3,3) - seqsize(1,2) - }, - /* ----- */ - /* Functions with many parameters with the same "type" have sequences like: - * push.c n1 push3.c n1 n2 n3 - * ;$par ;$par - * push.c n2 - - * ;$par - - * push.c n3 - - * ;$par - - * etc. etc. - * - * Similar sequences occur with PUSH, PUSH.s and PUSHADDR - */ - { - "push.c %1!;$par!push.c %2!;$par!push.c %3!;$par!push.c %4!;$par!push.c %5!", - "push5.c %1 %2 %3 %4 %5!", - seqsize(5,5) - seqsize(1,5) - }, - { - "push.c %1!;$par!push.c %2!;$par!push.c %3!;$par!push.c %4!", - "push4.c %1 %2 %3 %4!", - seqsize(4,4) - seqsize(1,4) - }, - { - "push.c %1!;$par!push.c %2!;$par!push.c %3!", - "push3.c %1 %2 %3!", - seqsize(3,3) - seqsize(1,3) - }, - { - "push.c %1!;$par!push.c %2!", - "push2.c %1 %2!", - seqsize(2,2) - seqsize(1,2) - }, - /* ----- */ - { - "push %1!;$par!push %2!;$par!push %3!;$par!push %4!;$par!push %5!", - "push5 %1 %2 %3 %4 %5!", - seqsize(5,5) - seqsize(1,5) - }, - { - "push %1!;$par!push %2!;$par!push %3!;$par!push %4!", - "push4 %1 %2 %3 %4!", - seqsize(4,4) - seqsize(1,4) - }, - { - "push %1!;$par!push %2!;$par!push %3!", - "push3 %1 %2 %3!", - seqsize(3,3) - seqsize(1,3) - }, - { - "push %1!;$par!push %2!", - "push2 %1 %2!", - seqsize(2,2) - seqsize(1,2) - }, - /* ----- */ - { - "push.s %1!;$par!push.s %2!;$par!push.s %3!;$par!push.s %4!;$par!push.s %5!", - "push5.s %1 %2 %3 %4 %5!", - seqsize(5,5) - seqsize(1,5) - }, - { - "push.s %1!;$par!push.s %2!;$par!push.s %3!;$par!push.s %4!", - "push4.s %1 %2 %3 %4!", - seqsize(4,4) - seqsize(1,4) - }, - { - "push.s %1!;$par!push.s %2!;$par!push.s %3!", - "push3.s %1 %2 %3!", - seqsize(3,3) - seqsize(1,3) - }, - { - "push.s %1!;$par!push.s %2!", - "push2.s %1 %2!", - seqsize(2,2) - seqsize(1,2) - }, - /* ----- */ - { - "push.adr %1!;$par!push.adr %2!;$par!push.adr %3!;$par!push.adr %4!;$par!push.adr %5!", - "push5.adr %1 %2 %3 %4 %5!", - seqsize(5,5) - seqsize(1,5) - }, - { - "push.adr %1!;$par!push.adr %2!;$par!push.adr %3!;$par!push.adr %4!", - "push4.adr %1 %2 %3 %4!", - seqsize(4,4) - seqsize(1,4) - }, - { - "push.adr %1!;$par!push.adr %2!;$par!push.adr %3!", - "push3.adr %1 %2 %3!", - seqsize(3,3) - seqsize(1,3) - }, - { - "push.adr %1!;$par!push.adr %2!", - "push2.adr %1 %2!", - seqsize(2,2) - seqsize(1,2) - }, - /* Loading two registers at a time - * load.pri n1 load.both n1 n2 - * load.alt n2 - - * -------------------------------------- - * load.alt n2 load.both n1 n2 - * load.pri n1 - - * -------------------------------------- - * load.s.pri n1 load.s.both n1 n2 - * load.s.alt n2 - - * -------------------------------------- - * load.s.alt n2 load.s.both n1 n2 - * load.s.pri n1 - - */ - { - "load.pri %1!load.alt %2!", - "load.both %1 %2!", - seqsize(2,2) - seqsize(1,2) - }, - { - "load.alt %2!load.pri %1!", - "load.both %1 %2!", - seqsize(2,2) - seqsize(1,2) - }, - { - "load.s.pri %1!load.s.alt %2!", - "load.s.both %1 %2!", - seqsize(2,2) - seqsize(1,2) - }, - { - "load.s.alt %2!load.s.pri %1!", - "load.s.both %1 %2!", - seqsize(2,2) - seqsize(1,2) - }, - /* Loading two registers and then pushing them occurs with user operators - * load.both n1 n2 push2 n1 n2 - * push.pri - - * push.alt - - * -------------------------------------- - * load.s.both n1 n2 push2.s n1 n2 - * push.pri - - * push.alt - - */ - { - "load.both %1 %2!push.pri!push.alt!", - "push2 %1 %2!", - seqsize(3,2) - seqsize(1,2) - }, - { - "load.s.both %1 %2!push.pri!push.alt!", - "push2.s %1 %2!", - seqsize(3,2) - seqsize(1,2) - }, - /* Load a constant in a variable - * const.pri n1 const n2 n1 - * stor.pri n2 - - * -------------------------------------- - * const.pri n1 const.s n2 n1 - * stor.s.pri n2 - - */ - { - "const.pri %1!stor.pri %2!", - "const %2 %1!", - seqsize(2,2) - seqsize(1,2) - }, - { - "const.pri %1!stor.s.pri %2!", - "const.s %2 %1!", - seqsize(2,2) - seqsize(1,2) - }, - /* ----- */ - { NULL, NULL, 0 } -}; diff --git a/sourcepawn/compiler/sc7.cpp b/sourcepawn/compiler/sc7.cpp deleted file mode 100644 index fd474523..00000000 --- a/sourcepawn/compiler/sc7.cpp +++ /dev/null @@ -1,653 +0,0 @@ -/* Pawn compiler - Staging buffer and optimizer - * - * The staging buffer - * ------------------ - * The staging buffer allows buffered output of generated code, deletion - * of redundant code, optimization by a tinkering process and reversing - * the ouput of evaluated expressions (which is used for the reversed - * evaluation of arguments in functions). - * Initially, stgwrite() writes to the file directly, but after a call to - * stgset(TRUE), output is redirected to the buffer. After a call to - * stgset(FALSE), stgwrite()'s output is directed to the file again. Thus - * only one routine is used for writing to the output, which can be - * buffered output or direct output. - * - * staging buffer variables: stgbuf - the buffer - * stgidx - current index in the staging buffer - * staging - if true, write to the staging buffer; - * if false, write to file directly. - * - * The peephole optimizer uses a dual "pipeline". The staging buffer (described - * above) gets optimized for each expression or sub-expression in a function - * call. The peephole optimizer is recursive, but it does not span multiple - * sub-expressions. However, the data gets written to a second buffer that - * behaves much like the staging buffer. This second buffer gathers all - * optimized strings from the staging buffer for a complete expression. The - * peephole optmizer then runs over this second buffer to find optimzations - * across function parameter boundaries. - * - * - * Copyright (c) ITB CompuPhase, 1997-2006 - * - * This software is provided "as-is", without any express or implied warranty. - * In no event will the authors be held liable for any damages arising from - * the use of this software. - * - * Permission is granted to anyone to use this software for any purpose, - * including commercial applications, and to alter it and redistribute it - * freely, subject to the following restrictions: - * - * 1. The origin of this software must not be misrepresented; you must not - * claim that you wrote the original software. If you use this software in - * a product, an acknowledgment in the product documentation would be - * appreciated but is not required. - * 2. Altered source versions must be plainly marked as such, and must not be - * misrepresented as being the original software. - * 3. This notice may not be removed or altered from any source distribution. - * - * Version: $Id$ - */ -#include -#include -#include /* for atoi() */ -#include -#include -#if defined FORTIFY - #include -#endif -#include "sc.h" - -#if defined _MSC_VER - #pragma warning(push) - #pragma warning(disable:4125) /* decimal digit terminates octal escape sequence */ -#endif - -#include "sc7-in.scp" - -#if defined _MSC_VER - #pragma warning(pop) -#endif - -static int stgstring(char *start,char *end); -static void stgopt(char *start,char *end,int (*outputfunc)(char *str)); - - -#define sSTG_GROW 512 -#define sSTG_MAX 20480 - -static char *stgbuf=NULL; -static int stgmax=0; /* current size of the staging buffer */ - -static char *stgpipe=NULL; -static int pipemax=0; /* current size of the stage pipe, a second staging buffer */ -static int pipeidx=0; - -#define CHECK_STGBUFFER(index) if ((int)(index)>=stgmax) grow_stgbuffer(&stgbuf, &stgmax, (index)+1) -#define CHECK_STGPIPE(index) if ((int)(index)>=pipemax) grow_stgbuffer(&stgpipe, &pipemax, (index)+1) - -static void grow_stgbuffer(char **buffer, int *curmax, int requiredsize) -{ - char *p; - int clear= (*buffer==NULL); /* if previously none, empty buffer explicitly */ - - assert(*curmaxsSTG_MAX) - error(FATAL_ERROR_OOM); - *curmax=requiredsize+sSTG_GROW; - if (*buffer!=NULL) - p=(char *)realloc(*buffer,*curmax*sizeof(char)); - else - p=(char *)malloc(*curmax*sizeof(char)); - if (p==NULL) - error(FATAL_ERROR_OOM); - *buffer=p; - if (clear) - **buffer='\0'; -} - -void stgbuffer_cleanup(void) -{ - if (stgbuf!=NULL) { - free(stgbuf); - stgbuf=NULL; - stgmax=0; - } /* if */ - if (stgpipe!=NULL) { - free(stgpipe); - stgpipe=NULL; - pipemax=0; - pipeidx=0; - } /* if */ -} - -/* the variables "stgidx" and "staging" are declared in "scvars.c" */ - -/* stgmark - * - * Copies a mark into the staging buffer. At this moment there are three - * possible marks: - * sSTARTREORDER identifies the beginning of a series of expression - * strings that must be written to the output file in - * reordered order - * sENDREORDER identifies the end of 'reverse evaluation' - * sEXPRSTART + idx only valid within a block that is evaluated in - * reordered order, it identifies the start of an - * expression; the "idx" value is the argument position - * - * Global references: stgidx (altered) - * stgbuf (altered) - * staging (referred to only) - */ -void stgmark(char mark) -{ - if (staging) { - CHECK_STGBUFFER(stgidx); - stgbuf[stgidx++]=mark; - } /* if */ -} - -static int rebuffer(char *str) -{ - if (sc_status==statWRITE) { - if (pipeidx>=2 && stgpipe[pipeidx-1]=='\0' && stgpipe[pipeidx-2]!='\n') - pipeidx-=1; /* overwrite last '\0' */ - while (*str!='\0') { /* copy to staging buffer */ - CHECK_STGPIPE(pipeidx); - stgpipe[pipeidx++]=*str++; - } /* while */ - CHECK_STGPIPE(pipeidx); - stgpipe[pipeidx++]='\0'; - } /* if */ - return TRUE; -} - -static int filewrite(char *str) -{ - if (sc_status==statWRITE) - return pc_writeasm(outf,str); - return TRUE; -} - -/* stgwrite - * - * Writes the string "st" to the staging buffer or to the output file. In the - * case of writing to the staging buffer, the terminating byte of zero is - * copied too, but... the optimizer can only work on complete lines (not on - * fractions of it. Therefore if the string is staged, if the last character - * written to the buffer is a '\0' and the previous-to-last is not a '\n', - * the string is concatenated to the last string in the buffer (the '\0' is - * overwritten). This also means an '\n' used in the middle of a string isn't - * recognized and could give wrong results with the optimizer. - * Even when writing to the output file directly, all strings are buffered - * until a whole line is complete. - * - * Global references: stgidx (altered) - * stgbuf (altered) - * staging (referred to only) - */ -void stgwrite(const char *st) -{ - int len; - - if (staging) { - assert(stgidx==0 || stgbuf!=NULL); /* staging buffer must be valid if there is (apparently) something in it */ - if (stgidx>=2 && stgbuf[stgidx-1]=='\0' && stgbuf[stgidx-2]!='\n') - stgidx-=1; /* overwrite last '\0' */ - while (*st!='\0') { /* copy to staging buffer */ - CHECK_STGBUFFER(stgidx); - stgbuf[stgidx++]=*st++; - } /* while */ - CHECK_STGBUFFER(stgidx); - stgbuf[stgidx++]='\0'; - } else { - len=(stgbuf!=NULL) ? strlen(stgbuf) : 0; - CHECK_STGBUFFER(len+strlen(st)+1); - strcat(stgbuf,st); - len=strlen(stgbuf); - if (len>0 && stgbuf[len-1]=='\n') { - filewrite(stgbuf); - stgbuf[0]='\0'; - } /* if */ - } /* if */ -} - -/* stgout - * - * Writes the staging buffer to the output file via stgstring() (for - * reversing expressions in the buffer) and stgopt() (for optimizing). It - * resets "stgidx". - * - * Global references: stgidx (altered) - * stgbuf (referred to only) - * staging (referred to only) - */ -void stgout(int index) -{ - int reordered=0; - int idx; - - if (!staging) - return; - assert(pipeidx==0); - - /* first pass: sub-expressions */ - if (sc_status==statWRITE) - reordered=stgstring(&stgbuf[index],&stgbuf[stgidx]); - stgidx=index; - - /* second pass: optimize the buffer created in the first pass */ - if (sc_status==statWRITE) { - if (reordered) { - stgopt(stgpipe,stgpipe+pipeidx,filewrite); - } else { - /* there is no sense in re-optimizing if the order of the sub-expressions - * did not change; so output directly - */ - for (idx=0; idx=0) - stack[arg].end=start-1; /* finish previous argument */ - arg=(unsigned char)*start - sEXPRSTART; - stack[arg].start=start+1; - if (arg>=argc) - argc=arg+1; - } /* if */ - start++; - } else { - start+=strlen(start)+1; - } /* if */ - } /* switch */ - } while (nest); /* enddo */ - if (arg>=0) - stack[arg].end=start-1; /* finish previous argument */ - while (argc>0) { - argc--; - stgstring(stack[argc].start,stack[argc].end); - } /* while */ - free(stack); - } else { - ptr=start; - while (ptr0) - filewrite(stgbuf); - } /* if */ - stgbuf[0]='\0'; -} - -/* phopt_init - * Initialize all sequence strings of the peehole optimizer. The strings - * are embedded in the .EXE file in compressed format, here we expand - * them (and allocate memory for the sequences). - */ -static SEQUENCE *sequences = sequences_cmp; - -int phopt_init(void) -{ - return TRUE; -} - -int phopt_cleanup(void) -{ - return FALSE; -} - -#define MAX_OPT_VARS 5 -#define MAX_OPT_CAT 5 /* max. values that are concatenated */ -#if sNAMEMAX > (PAWN_CELL_SIZE/4) * MAX_OPT_CAT - #define MAX_ALIAS sNAMEMAX -#else - #define MAX_ALIAS (PAWN_CELL_SIZE/4) * MAX_OPT_CAT -#endif - -static int matchsequence(const char *start,const char *end,const char *pattern, - char symbols[MAX_OPT_VARS][MAX_ALIAS+1], - int *match_length) -{ - int var,i; - char str[MAX_ALIAS+1]; - const char *start_org=start; - cell value; - char *ptr; - - *match_length=0; - for (var=0; var=end) - return FALSE; - switch (*pattern) { - case '%': /* new "symbol" */ - pattern++; - assert(isdigit(*pattern)); - var=atoi(pattern) - 1; - assert(var>=0 && var=0 && var=0 && var0) { /* delete a section */ - memmove(dest,dest+offset,dest_length-offset); - memset(dest+dest_length-offset,0xcc,offset); /* not needed, but for cleanlyness */ - } else if (offset<0) { /* insert a section */ - memmove(dest-offset, dest, dest_length); - } /* if */ - memcpy(dest, replace, repl_length); -} - -/* stgopt - * - * Optimizes the staging buffer by checking for series of instructions that - * can be coded more compact. The routine expects the lines in the staging - * buffer to be separated with '\n' and '\0' characters. - * - * The longest sequences should probably be checked first. - */ - -static void stgopt(char *start,char *end,int (*outputfunc)(char *str)) -{ - char symbols[MAX_OPT_VARS][MAX_ALIAS+1]; - int seq,match_length,repl_length; - int matches; - char *debut=start; /* save original start of the buffer */ - - assert(sequences!=NULL); - /* do not match anything if debug-level is maximum */ - if (pc_optimize>sOPTIMIZE_NONE && sc_status==statWRITE) { - do { - matches=0; - start=debut; - while (start=0); - if (*sequences[seq].find=='\0') { - if (pc_optimize==sOPTIMIZE_NOMACRO) { - break; /* don't look further */ - } else { - seq++; /* continue with next string */ - continue; - } /* if */ - } /* if */ - if (matchsequence(start,end,sequences[seq].find,symbols,&match_length)) { - char *replace=replacesequence(sequences[seq].replace,symbols,&repl_length); - /* If the replacement is bigger than the original section, we may need - * to "grow" the staging buffer. This is quite complex, due to the - * re-ordering of expressions that can also happen in the staging - * buffer. In addition, it should not happen: the peephole optimizer - * must replace sequences with *shorter* sequences, not longer ones. - * So, I simply forbid sequences that are longer than the ones they - * are meant to replace. - */ - assert(match_length>=repl_length); - if (match_length>=repl_length) { - strreplace(start,replace,match_length,repl_length,(int)(end-start)); - end-=match_length-repl_length; - free(replace); - code_idx-=sequences[seq].savesize; - seq=0; /* restart search for matches */ - matches++; - } else { - /* actually, we should never get here (match_length0); - } /* if (pc_optimize>sOPTIMIZE_NONE && sc_status==statWRITE) */ - - for (start=debut; start -#include -#include -#include -#include -#include "sc.h" - -#if !defined TRUE - #define FALSE 0 - #define TRUE 1 -#endif -#if !defined _MAX_PATH - #define _MAX_PATH 250 -#endif -#if !defined DIRSEP_CHAR - #if defined LINUX || defined __FreeBSD__ || defined __OpenBSD__ - #define DIRSEP_CHAR '/' - #elif defined macintosh - #define DIRSEP_CHAR ':' - #else - #define DIRSEP_CHAR '\\' - #endif -#endif - -#if !defined ELEMENTS - #define ELEMENTS(array) (sizeof(array) / sizeof(array[0])) -#endif - -#if !defined NO_CODEPAGE - -#if !defined MAXCODEPAGE - #define MAXCODEPAGE 12 /* typically "cp" + 4 digits + ".txt" */ -#endif -#define INVALID 0xffffu /* 0xffff and 0xfffe are invalid Unicode characters */ -#define LEADBYTE 0xfffeu - -struct wordpair { - unsigned short index; - wchar_t code; -}; -static char cprootpath[_MAX_PATH] = { DIRSEP_CHAR, '\0' }; -static wchar_t bytetable[256]; -static struct wordpair *wordtable = NULL; -static unsigned wordtablesize = 0; -static unsigned wordtabletop = 0; - - -/* read in a line delimited by '\r' or '\n'; do NOT store the '\r' or '\n' into - * the string and ignore empty lines - * returns 1 for success and 0 for failure - */ -static int cp_readline(FILE *fp,char *string,size_t size) -{ - size_t count=0; - int c; - assert(size>1); - while ((c=fgetc(fp))!=EOF && count0) /* '\r' or '\n' ends a string */ - break; - /* if count==0, the line started with a '\r' or '\n', or perhaps line - * ends in the file are '\r\n' and we read and stopped on the '\r' of - * the preceding line - */ - } else { - string[count++]=(char)c; - } /* if */ - } /* while */ - string[count]='\0'; - return count>0; -} - -/* cp_path() sets the directory where all codepage files must be found (if - * the parameter to cp_set() specifies a full path, that is used instead). - * The path is specified into two parts: root and directory; the full path - * for the codepage direcory is just the concatenation of the two, with a - * directory separator in between. The directory is given in two parts, - * because often a program already retrieves its "home" directory and the - * codepages are most conveniently stored in a subdirectory of this home - * directory. - */ -int cp_path(const char *root, const char *directory) -{ - size_t len1,len2; - int add_slash1,add_slash2; - - len1= (root!=NULL) ? strlen(root) : 0; - add_slash1= (len1==0 || root[len1-1]!=DIRSEP_CHAR); - len2= (directory!=NULL) ? strlen(directory) : 0; - add_slash2= (len2>0 && root[len2-1]!=DIRSEP_CHAR); - if (len1+add_slash1+len2+add_slash2>=(_MAX_PATH-MAXCODEPAGE)) - return FALSE; /* full filename may not fit */ - if (root!=NULL) - strcpy(cprootpath,root); - if (add_slash1) { - assert(len1==0 || cprootpath[len1]=='\0'); - cprootpath[len1]=DIRSEP_CHAR; - cprootpath[len1+1]='\0'; - } /* if */ - if (directory!=NULL) - strcat(cprootpath,directory); - if (add_slash2) { - assert(cprootpath[len1+add_slash1+len2]=='\0'); - cprootpath[len1+add_slash1+len2]=DIRSEP_CHAR; - cprootpath[len1+add_slash1+len2+1]='\0'; - } /* if */ - cp_set(NULL); /* start with a "linear" table (no translation) */ - return TRUE; -} - -/* cp_set() loads a codepage from a file. The name parameter may be a - * filename (including a full path) or it may be a partial codepage name. - * If the name parameter is NULL, the codepage is cleared to be a "linear" - * table (no translation). - * The following files are attempted to open (where specifies the - * value of the parameter): - * - * / - * /.txt - * /cp - * /cp.txt - */ -int cp_set(const char *name) -{ - char filename[_MAX_PATH]; - FILE *fp=NULL; - unsigned index; - - /* for name==NULL, set up an identity table */ - if (name==NULL || *name=='\0') { - if (wordtable!=NULL) { - free(wordtable); - wordtable=NULL; - wordtablesize=0; - wordtabletop=0; - } /* if */ - for (index=0; indexMAXCODEPAGE) - return 0; - assert(strlen(name)+strlen(cprootpath)<_MAX_PATH); - strcpy(filename,cprootpath); - strcat(filename,name); - fp=fopen(filename,"rt"); - } /* if */ - if (fp==NULL) { - /* try opening the file in the "root path" for codepages, with a ".txt" extension */ - if (strlen(name)+4>=MAXCODEPAGE) - return 0; - assert(strlen(filename)+4<_MAX_PATH); - strcat(filename,".txt"); - fp=fopen(filename,"rt"); - } /* if */ - if (fp==NULL) { - /* try opening the file in the "root path" for codepages, with "cp" prefixed before the name */ - if (strlen(name)+2>MAXCODEPAGE) - return 0; - assert(2+strlen(name)+strlen(cprootpath)<_MAX_PATH); - strcpy(filename,cprootpath); - strcat(filename,"cp"); - strcat(filename,name); - fp=fopen(filename,"rt"); - } /* if */ - if (fp==NULL) { - /* try opening the file in the "root path" for codepages, with "cp" prefixed an ".txt" appended */ - if (strlen(name)+2+4>MAXCODEPAGE) - return 0; - assert(strlen(filename)+4<_MAX_PATH); - strcat(filename,".txt"); - fp=fopen(filename,"rt"); - } /* if */ - if (fp==NULL) - return FALSE; /* all failed */ - - /* clear the tables */ - for (index=0; index0 && wordtable!=NULL)); - if (wordtable!=NULL) { - free(wordtable); - wordtable=NULL; - wordtablesize=0; - wordtabletop=0; - } /* if */ - - /* read in the table */ - while (cp_readline(fp,filename,sizeof filename)) { - char *ptr; - if ((ptr=strchr(filename,'#'))!=NULL) - *ptr='\0'; /* strip of comment */ - for (ptr=filename; *ptr>0 && *ptr<' '; ptr++) - /* nothing */; /* skip leading whitespace */ - if (*ptr!='\0') { - /* content on line */ - unsigned code=LEADBYTE; - int num=sscanf(ptr,"%i %i",&index,&code); - /* if sscanf() returns 1 and the index is in range 0..255, then the - * code is a DBCS lead byte; if sscanf() returns 2 and index>=256, this - * is a double byte pair (lead byte + follower) - */ - if (num>=1 && index<256) { - bytetable[index]=(wchar_t)code; - } else if (num==2 && index>=256 && index=wordtablesize) { - /* grow the list */ - int newsize; - struct wordpair *newblock; - newsize= (wordtablesize==0) ? 128 : 2*wordtablesize; - newblock=(struct wordpair *)malloc(newsize*sizeof(*wordtable)); - if (newblock!=NULL) { - memcpy(newblock,wordtable,wordtabletop*sizeof(*wordtable)); - free(wordtable); - wordtable=newblock; - wordtablesize=newsize; - } /* if */ - } /* if */ - if (wordtabletop0 && (unsigned)wordtable[pos-1].index>index) { - wordtable[pos]=wordtable[pos-1]; - pos--; - } /* while */ - wordtable[pos].index=(unsigned short)index; - wordtable[pos].code=(wchar_t)code; - } /* if */ - } /* if */ - } /* if */ - } /* while */ - - fclose(fp); - return TRUE; -} - -cell cp_translate(const unsigned char *string,const unsigned char **endptr) -{ - wchar_t result; - - result=bytetable[*string++]; - /* check whether this is a leader code */ - if ((unsigned)result==LEADBYTE && wordtable!=NULL) { - /* look up the code via binary search */ - int low,high,mid; - unsigned short index=(unsigned short)(((*(string-1)) << 8) | *string); - string++; - assert(wordtabletop>0); - low=0; - high=wordtabletop-1; - while (lowwordtable[mid].index) - low=mid+1; - else - high=mid; - } /* while */ - assert(low==high); - if (wordtable[low].index==index) - result=wordtable[low].code; - } /* if */ - - if (endptr!=NULL) - *endptr=string; - return (cell)result; -} - -#endif /* NO_CODEPAGE */ - -#if !defined NO_UTF8 -cell get_utf8_char(const unsigned char *string,const unsigned char **endptr) -{ - int follow=0; - long lowmark=0; - unsigned char ch; - cell result=0; - - if (endptr!=NULL) - *endptr=string; - - for ( ;; ) { - ch=*string++; - - if (follow>0 && (ch & 0xc0)==0x80) { - /* leader code is active, combine with earlier code */ - result=(result << 6) | (ch & 0x3f); - if (--follow==0) { - /* encoding a character in more bytes than is strictly needed, - * is not really valid UTF-8; we are strict here to increase - * the chance of heuristic dectection of non-UTF-8 text - * (JAVA writes zero bytes as a 2-byte code UTF-8, which is invalid) - */ - if (result=0xd800 && result<=0xdfff) || result==0xfffe || result==0xffff) - return -1; - } /* if */ - break; - } else if (follow==0 && (ch & 0x80)==0x80) { - /* UTF-8 leader code */ - if ((ch & 0xe0)==0xc0) { - /* 110xxxxx 10xxxxxx */ - follow=1; - lowmark=0x80L; - result=ch & 0x1f; - } else if ((ch & 0xf0)==0xe0) { - /* 1110xxxx 10xxxxxx 10xxxxxx (16 bits, BMP plane) */ - follow=2; - lowmark=0x800L; - result=ch & 0x0f; - } else if ((ch & 0xf8)==0xf0) { - /* 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx */ - follow=3; - lowmark=0x10000L; - result=ch & 0x07; - } else if ((ch & 0xfc)==0xf8) { - /* 111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx */ - follow=4; - lowmark=0x200000L; - result=ch & 0x03; - } else if ((ch & 0xfe)==0xfc) { - /* 1111110x 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx (32 bits) */ - follow=5; - lowmark=0x4000000L; - result=ch & 0x01; - } else { - /* this is invalid UTF-8 */ - return -1; - } /* if */ - } else if (follow==0 && (ch & 0x80)==0x00) { - /* 0xxxxxxx (US-ASCII) */ - result=ch; - break; - } else { - /* this is invalid UTF-8 */ - return -1; - } /* if */ - - } /* for */ - - if (endptr!=NULL) - *endptr=string; - return result; -} -#endif - -int scan_utf8(void *fp,const char *filename) -{ - #if defined NO_UTF8 - return 0; - #else - static void *resetpos=NULL; - int utf8=TRUE; - int firstchar=TRUE,bom_found=FALSE; - const unsigned char *ptr; - - resetpos=pc_getpossrc(fp,resetpos); - while (utf8 && pc_readsrc(fp,pline,sLINEMAX)!=NULL) { - ptr=pline; - if (firstchar) { - /* check whether the very first character on the very first line - * starts with a BYTE order mark - */ - cell c=get_utf8_char(ptr,&ptr); - bom_found= (c==0xfeff); - utf8= (c>=0); - firstchar=FALSE; - } /* if */ - while (utf8 && *ptr!='\0') - utf8= (get_utf8_char(ptr,&ptr)>=0); - } /* while */ - pc_resetsrc(fp,resetpos); - if (bom_found) { - unsigned char bom[3]; - if (!utf8) - error(77,filename); /* malformed UTF-8 encoding */ - pc_readsrc(fp,bom,3); - assert(bom[0]==0xef && bom[1]==0xbb && bom[2]==0xbf); - } /* if */ - return utf8; - #endif /* NO_UTF8 */ -} diff --git a/sourcepawn/compiler/sclinux.h b/sourcepawn/compiler/sclinux.h deleted file mode 100644 index 1ec9405c..00000000 --- a/sourcepawn/compiler/sclinux.h +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Things needed to compile under linux. - * - * Should be reworked totally to use GNU's 'configure' - */ -#ifndef SCLINUX_H -#define SCLINUX_H - -/* getchar() is not a 'cool' replacement for MSDOS getch: Linux/unix depends on the features activated or not about the - * controlling terminal's tty. This means that ioctl(2) calls must be performed, for instance to have the controlling - * terminal tty's in 'raw' mode, if we want to be able to fetch a single character. This also means that everything must - * be put back correctly when the function ends. See GETCH.C for an implementation. - * - * For interactive use of SRUN/SDBG if would be much better to use GNU's readline package: the user would be able to - * have a complete emacs/vi like line editing system. - */ -#include "getch.h" - -/* - * WinWorld wants '\'. Unices do not. - */ -#define DIRECTORY_SEP_CHAR '/' -#define DIRECTORY_SEP_STR "/" - -/* - * SC assumes that a computer is Little Endian unless told otherwise. It uses - * (and defines) the macros BYTE_ORDER and BIG_ENDIAN. - * For Linux, we must overrule these settings with those defined in glibc. - */ -#if !defined __BYTE_ORDER -# if defined EMSCRIPTEN -# include -# else -# include -# endif -#endif - -#if defined __OpenBSD__ || defined __FreeBSD__ || defined __APPLE__ -# define __BYTE_ORDER BYTE_ORDER -# define __LITTLE_ENDIAN LITTLE_ENDIAN -# define __BIG_ENDIAN BIG_ENDIAN -#endif - -#if !defined __BYTE_ORDER -# error "Can't figure computer byte order (__BYTE_ORDER macro not found)" -#endif - -#endif /* SCLINUX_H */ diff --git a/sourcepawn/compiler/sclist.cpp b/sourcepawn/compiler/sclist.cpp deleted file mode 100644 index a8cec15a..00000000 --- a/sourcepawn/compiler/sclist.cpp +++ /dev/null @@ -1,539 +0,0 @@ -/* Pawn compiler - maintenance of various lists - * - * o Name list (aliases) - * o Include path list - * o Macro definitions (text substitutions) - * o Documentation tags and automatic listings - * o Debug strings - * - * Copyright (c) ITB CompuPhase, 2001-2006 - * - * This software is provided "as-is", without any express or implied warranty. - * In no event will the authors be held liable for any damages arising from - * the use of this software. - * - * Permission is granted to anyone to use this software for any purpose, - * including commercial applications, and to alter it and redistribute it - * freely, subject to the following restrictions: - * - * 1. The origin of this software must not be misrepresented; you must not - * claim that you wrote the original software. If you use this software in - * a product, an acknowledgment in the product documentation would be - * appreciated but is not required. - * 2. Altered source versions must be plainly marked as such, and must not be - * misrepresented as being the original software. - * 3. This notice may not be removed or altered from any source distribution. - * - * Version: $Id$ - */ -#include -#include -#include -#include -#include "sc.h" -#include "lstring.h" - -#if defined FORTIFY - #include -#endif - -/* a "private" implementation of strdup(), so that porting - * to other memory allocators becomes easier. - * By Søren Hannibal. - */ -char* duplicatestring(const char* sourcestring) -{ - char* result=(char*)malloc(strlen(sourcestring)+1); - strcpy(result,sourcestring); - return result; -} - - -static stringpair *insert_stringpair(stringpair *root,const char *first,const char *second,int matchlength) -{ - stringpair *cur,*pred; - - assert(root!=NULL); - assert(first!=NULL); - assert(second!=NULL); - /* create a new node, and check whether all is okay */ - if ((cur=(stringpair*)malloc(sizeof(stringpair)))==NULL) - return NULL; - cur->first=duplicatestring(first); - cur->second=duplicatestring(second); - cur->matchlength=matchlength; - cur->documentation=NULL; - if (cur->first==NULL || cur->second==NULL) { - if (cur->first!=NULL) - free(cur->first); - if (cur->second!=NULL) - free(cur->second); - free(cur); - return NULL; - } /* if */ - /* link the node to the tree, find the position */ - for (pred=root; pred->next!=NULL && strcmp(pred->next->first,first)<0; pred=pred->next) - /* nothing */; - cur->next=pred->next; - pred->next=cur; - return cur; -} - -static void delete_stringpairtable(stringpair *root) -{ - stringpair *cur, *next; - - assert(root!=NULL); - cur=root->next; - while (cur!=NULL) { - next=cur->next; - assert(cur->first!=NULL); - assert(cur->second!=NULL); - free(cur->first); - free(cur->second); - free(cur); - cur=next; - } /* while */ - memset(root,0,sizeof(stringpair)); -} - -static stringpair *find_stringpair(stringpair *cur,char *first,int matchlength) -{ - int result=0; - - assert(matchlength>0); /* the function cannot handle zero-length comparison */ - assert(first!=NULL); - while (cur!=NULL && result<=0) { - result=(int)*cur->first - (int)*first; - if (result==0 && matchlength==cur->matchlength) { - result=strncmp(cur->first,first,matchlength); - if (result==0) - return cur; - } /* if */ - cur=cur->next; - } /* while */ - return NULL; -} - -static int delete_stringpair(stringpair *root,stringpair *item) -{ - stringpair *cur; - - assert(root!=NULL); - cur=root; - while (cur->next!=NULL) { - if (cur->next==item) { - cur->next=item->next; /* unlink from list */ - assert(item->first!=NULL); - assert(item->second!=NULL); - free(item->first); - free(item->second); - free(item); - return TRUE; - } /* if */ - cur=cur->next; - } /* while */ - return FALSE; -} - -/* ----- string list functions ----------------------------------- */ -static stringlist *insert_string(stringlist *root,const char *string) -{ - stringlist *cur; - - assert(string!=NULL); - if ((cur=(stringlist*)malloc(sizeof(stringlist)))==NULL) - error(103); /* insufficient memory (fatal error) */ - if ((cur->line=duplicatestring(string))==NULL) - error(103); /* insufficient memory (fatal error) */ - cur->next=NULL; - if (root->tail) - root->tail->next=cur; - else - root->next=cur; - root->tail=cur; - return cur; -} - -static char *get_string(stringlist *root,int index) -{ - stringlist *cur; - - assert(root!=NULL); - cur=root->next; - while (cur!=NULL && index-->0) - cur=cur->next; - if (cur!=NULL) { - assert(cur->line!=NULL); - return cur->line; - } /* if */ - return NULL; -} - -static int delete_string(stringlist *root,int index) -{ - stringlist *cur,*item; - - assert(root!=NULL); - for (cur=root; cur->next!=NULL && index>0; cur=cur->next,index--) - /* nothing */; - if (cur->next!=NULL) { - item=cur->next; - if (root->tail == cur->next) - root->tail = cur; - cur->next=item->next; /* unlink from list */ - assert(item->line!=NULL); - free(item->line); - free(item); - return TRUE; - } /* if */ - return FALSE; -} - -void delete_stringtable(stringlist *root) -{ - stringlist *cur,*next; - - assert(root!=NULL); - cur=root->next; - while (cur!=NULL) { - next=cur->next; - assert(cur->line!=NULL); - free(cur->line); - free(cur); - cur=next; - } /* while */ - memset(root,0,sizeof(stringlist)); -} - - -/* ----- alias table --------------------------------------------- */ -static stringpair alias_tab = {NULL, NULL, NULL}; /* alias table */ - -stringpair *insert_alias(char *name,char *alias) -{ - stringpair *cur; - - assert(name!=NULL); - assert(strlen(name)<=sNAMEMAX); - assert(alias!=NULL); - assert(strlen(alias)<=sNAMEMAX); - if ((cur=insert_stringpair(&alias_tab,name,alias,strlen(name)))==NULL) - error(103); /* insufficient memory (fatal error) */ - return cur; -} - -int lookup_alias(char *target,char *name) -{ - stringpair *cur=find_stringpair(alias_tab.next,name,strlen(name)); - if (cur!=NULL) { - assert(strlen(cur->second)<=sNAMEMAX); - strcpy(target,cur->second); - } /* if */ - return cur!=NULL; -} - -void delete_aliastable(void) -{ - delete_stringpairtable(&alias_tab); -} - -/* ----- include paths list -------------------------------------- */ -static stringlist includepaths; /* directory list for include files */ - -stringlist *insert_path(char *path) -{ - return insert_string(&includepaths,path); -} - -char *get_path(int index) -{ - return get_string(&includepaths,index); -} - -void delete_pathtable(void) -{ - delete_stringtable(&includepaths); - assert(includepaths.next==NULL); -} - - -/* ----- text substitution patterns ------------------------------ */ -#if !defined NO_DEFINE - -static stringpair substpair = { NULL, NULL, NULL}; /* list of substitution pairs */ - -static stringpair *substindex['z'-PUBLIC_CHAR+1]; /* quick index to first character */ -static void adjustindex(char c) -{ - stringpair *cur; - assert((c>='A' && c<='Z') || (c>='a' && c<='z') || c=='_' || c==PUBLIC_CHAR); - assert(PUBLIC_CHAR<'A' && 'A'<'_' && '_'<'z'); - - for (cur=substpair.next; cur!=NULL && cur->first[0]!=c; cur=cur->next) - /* nothing */; - substindex[(int)c-PUBLIC_CHAR]=cur; -} - -stringpair *insert_subst(const char *pattern,const char *substitution,int prefixlen) -{ - stringpair *cur; - - assert(pattern!=NULL); - assert(substitution!=NULL); - if ((cur=insert_stringpair(&substpair,pattern,substitution,prefixlen))==NULL) - error(103); /* insufficient memory (fatal error) */ - adjustindex(*pattern); - - if (pc_deprecate!=NULL) { - assert(cur!=NULL); - cur->flags|=flgDEPRECATED; - if (sc_status==statWRITE) { - if (cur->documentation!=NULL) { - free(cur->documentation); - cur->documentation=NULL; - } /* if */ - cur->documentation=pc_deprecate; - } else { - free(pc_deprecate); - } /* if */ - pc_deprecate=NULL; - } else { - cur->flags = 0; - cur->documentation = NULL; - } /* if */ - - return cur; -} - -stringpair *find_subst(char *name,int length) -{ - stringpair *item; - assert(name!=NULL); - assert(length>0); - assert((*name>='A' && *name<='Z') || (*name>='a' && *name<='z') || *name=='_' || *name==PUBLIC_CHAR); - item=substindex[(int)*name-PUBLIC_CHAR]; - if (item!=NULL) - item=find_stringpair(item,name,length); - - if (item && (item->flags & flgDEPRECATED) != 0) - { - static char macro[128]; - const char *msg = (item->documentation != NULL) ? item->documentation : ""; - strlcpy(macro, item->first, sizeof(macro)); - - /* If macro contains an opening parentheses and a percent sign, then assume that - * it takes arguments and remove them from the warning message. - */ - char *rem; - if ((rem = strchr(macro, '(')) != NULL && strchr(macro, '%') > rem) - { - *rem = '\0'; - } - - error(234, macro, msg); /* deprecated (macro/constant) */ - } - return item; -} - -int delete_subst(char *name,int length) -{ - stringpair *item; - assert(name!=NULL); - assert(length>0); - assert((*name>='A' && *name<='Z') || (*name>='a' && *name<='z') || *name=='_' || *name==PUBLIC_CHAR); - item=substindex[(int)*name-PUBLIC_CHAR]; - if (item!=NULL) - item=find_stringpair(item,name,length); - if (item==NULL) - return FALSE; - if (item->documentation) - { - free(item->documentation); - item->documentation=NULL; - } - delete_stringpair(&substpair,item); - adjustindex(*name); - return TRUE; -} - -void delete_substtable(void) -{ - size_t i; - delete_stringpairtable(&substpair); - for (i=0; i=199901L - #define __STDC_FORMAT_MACROS - #define __STDC_CONSTANT_MACROS - #include /* automatically includes stdint.h */ -#elif (defined _MSC_VER || defined __BORLANDC__) && (defined _I64_MAX || defined HAVE_I64) - #define PRId64 "I64d" - #define PRIx64 "I64x" -#else - #define PRId64 "lld" - #define PRIx64 "llx" -#endif -#if PAWN_CELL_SIZE==64 - #define PRIdC PRId64 - #define PRIxC PRIx64 -#elif PAWN_CELL_SIZE==32 - #define PRIdC "ld" - #define PRIxC "lx" -#else - #define PRIdC "d" - #define PRIxC "x" -#endif - -static stringlist dbgstrings; - -stringlist *insert_dbgfile(const char *filename) -{ - - if (sc_status==statWRITE && (sc_debug & sSYMBOLIC)!=0) { - char string[_MAX_PATH+40]; - assert(filename!=NULL); - assert(strlen(filename)+400) - linenr--; /* line numbers are zero-based in the debug information */ - sprintf(string,"L:%" PRIxC " %x",code_idx,linenr); - return insert_string(&dbgstrings,string); - } /* if */ - return NULL; -} - -stringlist *insert_dbgsymbol(symbol *sym) -{ - if (sc_status==statWRITE && (sc_debug & sSYMBOLIC)!=0) { - char string[2*sNAMEMAX+128]; - char symname[2*sNAMEMAX+16]; - - funcdisplayname(symname,sym->name); - /* address tag:name codestart codeend ident vclass [tag:dim ...] */ - if (sym->ident==iFUNCTN) { - sprintf(string,"S:%" PRIxC " %x:%s %" PRIxC " %" PRIxC " %x %x", - sym->addr,sym->tag,symname,sym->addr,sym->codeaddr,sym->ident,sym->vclass); - } else { - sprintf(string,"S:%" PRIxC " %x:%s %" PRIxC " %" PRIxC " %x %x", - sym->addr,sym->tag,symname,sym->codeaddr,code_idx,sym->ident,sym->vclass); - } /* if */ - if (sym->ident==iARRAY || sym->ident==iREFARRAY) { - #if !defined NDEBUG - int count=sym->dim.array.level; - #endif - symbol *sub; - strcat(string," [ "); - for (sub=sym; sub!=NULL; sub=finddepend(sub)) { - assert(sub->dim.array.level==count--); - sprintf(string+strlen(string),"%x:%x ",sub->x.tags.index,sub->dim.array.length); - } /* for */ - strcat(string,"]"); - } /* if */ - - return insert_string(&dbgstrings,string); - } /* if */ - return NULL; -} - -stringlist *get_dbgstrings() -{ - return &dbgstrings; -} - -char *get_dbgstring(int index) -{ - return get_string(&dbgstrings,index); -} - -void delete_dbgstringtable(void) -{ - delete_stringtable(&dbgstrings); - assert(dbgstrings.next==NULL); -} diff --git a/sourcepawn/compiler/scmemfil.cpp b/sourcepawn/compiler/scmemfil.cpp deleted file mode 100644 index 59eb3875..00000000 --- a/sourcepawn/compiler/scmemfil.cpp +++ /dev/null @@ -1,165 +0,0 @@ -/* Pawn compiler - * - * Routines to maintain a "text file" in memory. - * - * Copyright (c) ITB CompuPhase, 2003-2006 - * - * This software is provided 'as-is', without any express or implied warranty. - * In no event will the authors be held liable for any damages arising from the - * use of this software. - * - * Permission is granted to anyone to use this software for any purpose, - * including commercial applications, and to alter it and redistribute it - * freely, subject to the following restrictions: - * - * 1. The origin of this software must not be misrepresented; you must not - * claim that you wrote the original software. If you use this software in - * a product, an acknowledgment in the product documentation would be - * appreciated but is not required. - * - * 2. Altered source versions must be plainly marked as such, and must not be - * misrepresented as being the original software. - * - * 3. This notice may not be removed or altered from any source distribution. - * - * Version: $Id$ - */ - -#include -#include -#include -#include -#include "memfile.h" - -#if defined FORTIFY - #include -#endif - -#include "sc.h" - -MEMFILE *mfcreate(const char *filename) -{ - return memfile_creat(filename, 4096); -} - -void mfclose(MEMFILE *mf) -{ - memfile_destroy(mf); -} - -int mfdump(MEMFILE *mf) -{ - FILE *fp; - int okay; - - assert(mf!=NULL); - /* create the file */ - fp=fopen(mf->name, "wb"); - if (fp==NULL) - return 0; - - okay=1; - okay = okay & (fwrite(mf->base, mf->usedoffs, 1, fp)==(size_t)mf->usedoffs); - - fclose(fp); - return okay; -} - -long mflength(const MEMFILE *mf) -{ - return mf->usedoffs; -} - -long mfseek(MEMFILE *mf,long offset,int whence) -{ - long length; - - assert(mf!=NULL); - if (mf->usedoffs == 0) - return 0L; /* early exit: not a single byte in the file */ - - /* find the size of the memory file */ - length=mflength(mf); - - /* convert the offset to an absolute position */ - switch (whence) { - case SEEK_SET: - break; - case SEEK_CUR: - offset+=mf->offs; - break; - case SEEK_END: - assert(offset<=0); - offset+=length; - break; - } /* switch */ - - /* clamp to the file length limit */ - if (offset<0) - offset=0; - else if (offset>length) - offset=length; - - /* set new position and return it */ - memfile_seek(mf, offset); - - return offset; -} - -unsigned int mfwrite(MEMFILE *mf,const unsigned char *buffer,unsigned int size) -{ - return (memfile_write(mf, buffer, size) ? size : 0); -} - -unsigned int mfread(MEMFILE *mf,unsigned char *buffer,unsigned int size) -{ - return memfile_read(mf, buffer, size); -} - -char *mfgets(MEMFILE *mf,char *string,unsigned int size) -{ - char *ptr; - unsigned int read; - long seek; - - assert(mf!=NULL); - - read=mfread(mf,(unsigned char *)string,size); - if (read==0) - return NULL; - seek=0L; - - /* make sure that the string is zero-terminated */ - assert(read<=size); - if (read -#include -#include -#include -#include -#include "sc.h" -#if defined LINUX || defined __FreeBSD__ || defined __OpenBSD__ - #include "sclinux.h" -#endif - -#if defined FORTIFY - #include -#endif - -typedef struct s_statelist { - struct s_statelist *next; - int *states; /* list of states in this combination */ - int numstates; /* number of items in the above list */ - int fsa; /* automaton id */ - int listid; /* unique id for this combination list */ -} statelist; - -static statelist statelist_tab = { NULL, NULL, 0, 0, 0}; /* state combinations table */ - - -static constvalue *find_automaton(const char *name,int *last) -{ - constvalue *ptr; - - assert(last!=NULL); - *last=0; - ptr=sc_automaton_tab.next; - while (ptr!=NULL) { - if (strcmp(name,ptr->name)==0) - return ptr; - if (ptr->index>*last) - *last=ptr->index; - ptr=ptr->next; - } /* while */ - return NULL; -} - -constvalue *automaton_add(const char *name) -{ - constvalue *ptr; - int last; - - assert(strlen(name)name)); - ptr=find_automaton(name,&last); - if (ptr==NULL) { - assert(last+1 <= SHRT_MAX); - ptr=append_constval(&sc_automaton_tab,name,(cell)0,(short)(last+1)); - } /* if */ - return ptr; -} - -constvalue *automaton_find(const char *name) -{ - int last; - return find_automaton(name,&last); -} - -constvalue *automaton_findid(int id) -{ - constvalue *ptr; - for (ptr=sc_automaton_tab.next; ptr!=NULL && ptr->index!=id; ptr=ptr->next) - /* nothing */; - return ptr; -} - - -static constvalue *find_state(const char *name,int fsa,int *last) -{ - constvalue *ptr; - - assert(last!=NULL); - *last=0; - ptr=sc_state_tab.next; - while (ptr!=NULL) { - if (ptr->index==fsa) { - if (strcmp(name,ptr->name)==0) - return ptr; - if ((int)ptr->value>*last) - *last=(int)ptr->value; - } /* if */ - ptr=ptr->next; - } /* while */ - return NULL; -} - -constvalue *state_add(const char *name,int fsa) -{ - constvalue *ptr; - int last; - - assert(strlen(name)name)); - ptr=find_state(name,fsa,&last); - if (ptr==NULL) { - assert(fsa <= SHRT_MAX); - ptr=append_constval(&sc_state_tab,name,(cell)(last+1),(short)fsa); - } /* if */ - return ptr; -} - -constvalue *state_find(const char *name,int fsa_id) -{ - int last; /* dummy */ - return find_state(name,fsa_id,&last); -} - -constvalue *state_findid(int id) -{ - constvalue *ptr; - for (ptr=sc_state_tab.next; ptr!=NULL && ptr->value!=id; ptr=ptr->next) - /* nothing */; - return ptr; -} - -void state_buildlist(int **list,int *listsize,int *count,int stateid) -{ - int idx; - - assert(list!=NULL); - assert(listsize!=NULL); - assert(*listsize>=0); - assert(count!=NULL); - assert(*count>=0); - assert(*count<=*listsize); - - if (*count==*listsize) { - /* To avoid constantly calling malloc(), the list is grown by 4 states at - * a time. - */ - *listsize+=4; - *list=(int*)realloc(*list,*listsize*sizeof(int)); - if (*list==NULL) - error(103); /* insufficient memory */ - } /* if */ - - /* find the insertion point (the list has to stay sorted) */ - for (idx=0; idx<*count && *list[idx]0); - assert(last!=NULL); - *last=0; - ptr=statelist_tab.next; - while (ptr!=NULL) { - if (ptr->listid>*last) - *last=ptr->listid; - if (ptr->fsa==fsa && ptr->numstates==count) { - /* compare all states */ - for (i=0; istates[i]==list[i]; i++) - /* nothing */; - if (i==count) - return ptr; - } /* if */ - ptr=ptr->next; - } /* while */ - return NULL; -} - -static statelist *state_getlist_ptr(int listid) -{ - statelist *ptr; - - assert(listid>0); - for (ptr=statelist_tab.next; ptr!=NULL && ptr->listid!=listid; ptr=ptr->next) - /* nothing */; - return ptr; -} - -int state_addlist(int *list,int count,int fsa) -{ - statelist *ptr; - int last; - - assert(list!=NULL); - assert(count>0); - ptr=state_findlist(list,count,fsa,&last); - if (ptr==NULL) { - if ((ptr=(statelist*)malloc(sizeof(statelist)))==NULL) - error(103); /* insufficient memory */ - if ((ptr->states=(int*)malloc(count*sizeof(int)))==NULL) { - free(ptr); - error(103); /* insufficient memory */ - } /* if */ - memcpy(ptr->states,list,count*sizeof(int)); - ptr->numstates=count; - ptr->fsa=fsa; - ptr->listid=last+1; - ptr->next=statelist_tab.next; - statelist_tab.next=ptr; - } /* if */ - assert(ptr!=NULL); - return ptr->listid; -} - -void state_deletetable(void) -{ - statelist *ptr; - - while (statelist_tab.next!=NULL) { - ptr=statelist_tab.next; - /* unlink first */ - statelist_tab.next=ptr->next; - /* then delete */ - assert(ptr->states!=NULL); - free(ptr->states); - free(ptr); - } /* while */ -} - -int state_getfsa(int listid) -{ - statelist *ptr; - - assert(listid>=0); - if (listid==0) - return -1; - - ptr=state_getlist_ptr(listid); - return (ptr!=NULL) ? ptr->fsa : -1; /* fsa 0 exists */ -} - -int state_count(int listid) -{ - statelist *ptr=state_getlist_ptr(listid); - if (ptr==NULL) - return 0; /* unknown list, no states in it */ - return ptr->numstates; -} - -int state_inlist(int listid,int state) -{ - statelist *ptr; - int i; - - ptr=state_getlist_ptr(listid); - if (ptr==NULL) - return FALSE; /* unknown list, state not in it */ - for (i=0; inumstates; i++) - if (ptr->states[i]==state) - return TRUE; - return FALSE; -} - -int state_listitem(int listid,int index) -{ - statelist *ptr; - - ptr=state_getlist_ptr(listid); - assert(ptr!=NULL); - assert(index>=0 && indexnumstates); - return ptr->states[index]; -} - -static int checkconflict(statelist *psrc,statelist *ptgt) -{ - int s,t; - - assert(psrc!=NULL); - assert(ptgt!=NULL); - for (s=0; snumstates; s++) - for (t=0; tnumstates; t++) - if (psrc->states[s]==ptgt->states[t]) - return 1; /* state conflict */ - return 0; -} - -/* This function searches whether one of the states in the list of statelist id's - * of a symbol exists in any other statelist id's of the same function; it also - * verifies that all definitions of the symbol are in the same automaton. - */ -void state_conflict(symbol *root) -{ - statelist *psrc,*ptgt; - constvalue *srcptr,*tgtptr; - symbol *sym; - - assert(root!=NULL); - for (sym=root->next; sym!=NULL; sym=sym->next) { - if (sym->parent!=NULL || sym->ident!=iFUNCTN) - continue; /* hierarchical data type or no function */ - if (sym->states==NULL) - continue; /* this function has no states */ - for (srcptr=sym->states->next; srcptr!=NULL; srcptr=srcptr->next) { - if (srcptr->index==-1) - continue; /* state list id -1 is a special case */ - psrc=state_getlist_ptr(srcptr->index); - assert(psrc!=NULL); - for (tgtptr=srcptr->next; tgtptr!=NULL; tgtptr=tgtptr->next) { - if (tgtptr->index==-1) - continue; /* state list id -1 is a special case */ - ptgt=state_getlist_ptr(tgtptr->index); - assert(ptgt!=NULL); - if (psrc->fsa!=ptgt->fsa && strcmp(sym->name,uENTRYFUNC)!=0) - error(83,sym->name); /* this function is part of another machine */ - if (checkconflict(psrc,ptgt)) - error(84,sym->name); /* state conflict */ - } /* for (tgtptr) */ - } /* for (srcptr) */ - } /* for (sym) */ -} - -/* check whether the two state lists (whose ids are passed in) share any - * states - */ -int state_conflict_id(int listid1,int listid2) -{ - statelist *psrc,*ptgt; - - psrc=state_getlist_ptr(listid1); - assert(psrc!=NULL); - ptgt=state_getlist_ptr(listid2); - assert(ptgt!=NULL); - return checkconflict(psrc,ptgt); -} diff --git a/sourcepawn/compiler/sctracker.cpp b/sourcepawn/compiler/sctracker.cpp deleted file mode 100644 index b575adcf..00000000 --- a/sourcepawn/compiler/sctracker.cpp +++ /dev/null @@ -1,614 +0,0 @@ -/* vim: set ts=8 sts=2 sw=2 tw=99 et: */ -#include -#include -#include -#include -#include "sc.h" -#include "sctracker.h" - -memuse_list_t *heapusage = NULL; -memuse_list_t *stackusage = NULL; -funcenum_t *firstenum = NULL; -funcenum_t *lastenum = NULL; -pstruct_t *firststruct = NULL; -pstruct_t *laststruct = NULL; -methodmap_t *methodmap_first = NULL; -methodmap_t *methodmap_last = NULL; - -structarg_t *pstructs_getarg(pstruct_t *pstruct, const char *member) -{ - int i; - - for (i=0; iargcount; i++) { - if (strcmp(pstruct->args[i]->name, member) == 0) - return pstruct->args[i]; - } - - return NULL; -} - -pstruct_t *pstructs_add(const char *name) -{ - pstruct_t *p = (pstruct_t *)malloc(sizeof(pstruct_t)); - - memset(p, 0, sizeof(pstruct_t)); - strcpy(p->name, name); - - if (!firststruct) { - firststruct = p; - laststruct = p; - } else { - laststruct->next = p; - laststruct = p; - } - - return p; -} - -void pstructs_free() -{ - pstruct_t *p, *next; - - p = firststruct; - while (p) { - while (p->argcount--) - free(p->args[p->argcount]); - free(p->args); - next = p->next; - free(p); - p = next; - } - firststruct = NULL; - laststruct = NULL; -} - -pstruct_t *pstructs_find(const char *name) -{ - pstruct_t *p = firststruct; - - while (p) { - if (strcmp(p->name, name) == 0) - return p; - p = p->next; - } - - return NULL; -} - -structarg_t *pstructs_addarg(pstruct_t *pstruct, const structarg_t *arg) -{ - structarg_t *newarg; - int i; - - for (i=0; iargcount; i++) { - if (strcmp(pstruct->args[i]->name, arg->name) == 0) { - /* Don't allow dup names */ - return NULL; - } - } - - newarg = (structarg_t *)malloc(sizeof(structarg_t)); - - memcpy(newarg, arg, sizeof(structarg_t)); - - if (pstruct->argcount == 0) { - pstruct->args = (structarg_t **)malloc(sizeof(structarg_t *) * 1); - } else { - pstruct->args = (structarg_t **)realloc( - pstruct->args, - sizeof(structarg_t *) * (pstruct->argcount + 1)); - } - - newarg->offs = pstruct->argcount * sizeof(cell); - newarg->index = pstruct->argcount; - pstruct->args[pstruct->argcount++] = newarg; - - return newarg; -} - -void funcenums_free() -{ - funcenum_t *e, *next; - - e = firstenum; - while (e) { - functag_t *tag, *nexttag; - tag = e->first; - while (tag) { - nexttag = tag->next; - free(tag); - tag = nexttag; - } - next = e->next; - free(e); - e = next; - } - - firstenum = NULL; - lastenum = NULL; -} - -funcenum_t *funcenums_find_by_tag(int tag) -{ - funcenum_t *e = firstenum; - - while (e) { - if (e->tag == tag) - return e; - e = e->next; - } - - return NULL; -} - -funcenum_t *funcenums_add(const char *name) -{ - funcenum_t *e = (funcenum_t *)malloc(sizeof(funcenum_t)); - - memset(e, 0, sizeof(funcenum_t)); - - if (!firstenum) { - firstenum = e; - lastenum = e; - } else { - lastenum->next = e; - lastenum = e; - } - - strcpy(e->name, name); - e->tag = pc_addtag_flags((char *)name, FIXEDTAG|FUNCTAG); - - return e; -} - -funcenum_t *funcenum_for_symbol(symbol *sym) -{ - functag_t ft; - memset(&ft, 0, sizeof(ft)); - - ft.ret_tag = sym->tag; - ft.usage = uPUBLIC & (sym->usage & uRETVALUE); - ft.argcount = 0; - ft.ommittable = FALSE; - for (arginfo *arg = sym->dim.arglist; arg->ident; arg++) { - funcarg_t *dest = &ft.args[ft.argcount++]; - - dest->tagcount = arg->numtags; - memcpy(dest->tags, arg->tags, arg->numtags * sizeof(int)); - - dest->dimcount = arg->numdim; - memcpy(dest->dims, arg->dim, arg->numdim * sizeof(int)); - - dest->ident = arg->ident; - dest->fconst = !!(arg->usage & uCONST); - dest->ommittable = FALSE; - } - - char name[METHOD_NAMEMAX+1]; - UTIL_Format(name, sizeof(name), "::ft:%s:%d:%d", sym->name, sym->addr, sym->codeaddr); - - funcenum_t *fe = funcenums_add(name); - functags_add(fe, &ft); - - return fe; -} - -// Finds a functag that was created intrinsically. -functag_t *functag_find_intrinsic(int tag) -{ - funcenum_t *fe = funcenums_find_by_tag(tag); - if (!fe) - return NULL; - - if (strncmp(fe->name, "::ft:", 5) != 0) - return NULL; - - assert(fe->first && fe->first == fe->last); - return fe->first; -} - -functag_t *functags_add(funcenum_t *en, functag_t *src) -{ - functag_t *t = (functag_t *)malloc(sizeof(functag_t)); - - memcpy(t, src, sizeof(functag_t)); - - t->next = NULL; - - if (en->first == NULL) { - en->first = t; - en->last = t; - } else { - en->last->next = t; - en->last = t; - } - - return t; -} - -/** - * Creates a new mem usage tracker entry - */ -void _push_memlist(memuse_list_t **head) -{ - memuse_list_t *newlist = (memuse_list_t *)malloc(sizeof(memuse_list_t)); - if (*head != NULL) - { - newlist->list_id = (*head)->list_id + 1; - } else { - newlist->list_id = 0; - } - newlist->prev = *head; - newlist->head = NULL; - *head = newlist; -} - -/** - * Pops a heap list but does not free it. - */ -memuse_list_t *_pop_save_memlist(memuse_list_t **head) -{ - memuse_list_t *oldlist = *head; - *head = (*head)->prev; - return oldlist; -} - -/** - * Marks a memory usage on a memory list - */ -int _mark_memlist(memuse_list_t *head, int type, int size) -{ - memuse_t *use; - if (type==MEMUSE_STATIC && size==0) - { - return 0; - } - use=head->head; - if (use && (type==MEMUSE_STATIC) - && (use->type == type)) - { - use->size += size; - } else { - use=(memuse_t *)malloc(sizeof(memuse_t)); - use->type=type; - use->size=size; - use->prev=head->head; - head->head=use; - } - return size; -} - -void _reset_memlist(memuse_list_t **head) -{ - memuse_list_t *curlist = *head; - memuse_list_t *tmplist; - while (curlist) { - memuse_t *curuse = curlist->head; - memuse_t *tmpuse; - while (curuse) { - tmpuse = curuse->prev; - free(curuse); - curuse = tmpuse; - } - tmplist = curlist->prev; - free(curlist); - curlist = tmplist; - } - *head = NULL; -} - - -/** - * Wrapper for pushing the heap list - */ -void pushheaplist() -{ - _push_memlist(&heapusage); -} - -/** - * Wrapper for popping and saving the heap list - */ -memuse_list_t *popsaveheaplist() -{ - return _pop_save_memlist(&heapusage); -} - -/** - * Wrapper for marking the heap - */ -int markheap(int type, int size) -{ - return _mark_memlist(heapusage, type, size); -} - -/** - * Wrapper for pushing the stack list - */ -void pushstacklist() -{ - _push_memlist(&stackusage); -} - -/** - * Wrapper for marking the stack - */ -int markstack(int type, int size) -{ - return _mark_memlist(stackusage, type, size); -} - -/** - * Generates code to free all heap allocations on a tracker - */ -void _heap_freeusage(memuse_list_t *heap, int dofree) -{ - memuse_t *cur=heap->head; - memuse_t *tmp; - while (cur) { - if (cur->type == MEMUSE_STATIC) { - modheap((-1)*cur->size*sizeof(cell)); - } else { - modheap_i(); - } - if (dofree) { - tmp=cur->prev; - free(cur); - cur=tmp; - } else { - cur=cur->prev; - } - } - if (dofree) - heap->head=NULL; -} - -void _stack_genusage(memuse_list_t *stack, int dofree) -{ - memuse_t *cur = stack->head; - memuse_t *tmp; - while (cur) - { - if (cur->type == MEMUSE_DYNAMIC) - { - /* no idea yet */ - assert(0); - } else { - modstk(cur->size * sizeof(cell)); - } - if (dofree) - { - tmp = cur->prev; - free(cur); - cur = tmp; - } else { - cur = cur->prev; - } - } - if (dofree) - { - stack->head = NULL; - } -} - -/** - * Pops a heap list and frees it. - */ -void popheaplist() -{ - memuse_list_t *oldlist; - assert(heapusage!=NULL); - - _heap_freeusage(heapusage, 1); - assert(heapusage->head==NULL); - - oldlist=heapusage->prev; - free(heapusage); - heapusage=oldlist; -} - -void genstackfree(int stop_id) -{ - memuse_list_t *curlist = stackusage; - while (curlist && curlist->list_id > stop_id) - { - _stack_genusage(curlist, 0); - curlist = curlist->prev; - } -} - -void genheapfree(int stop_id) -{ - memuse_list_t *curlist = heapusage; - while (curlist && curlist->list_id > stop_id) - { - _heap_freeusage(curlist, 0); - curlist = curlist->prev; - } -} - -void popstacklist(int codegen) -{ - memuse_list_t *oldlist; - assert(stackusage != NULL); - - if (codegen) - { - _stack_genusage(stackusage, 1); - assert(stackusage->head==NULL); - } else { - memuse_t *use = stackusage->head; - while (use) { - memuse_t *temp = use->prev; - free(use); - use = temp; - } - } - - oldlist = stackusage->prev; - free(stackusage); - stackusage = oldlist; -} - -void resetstacklist() -{ - _reset_memlist(&stackusage); -} - -void resetheaplist() -{ - _reset_memlist(&heapusage); -} - -void methodmap_add(methodmap_t *map) -{ - if (!methodmap_first) { - methodmap_first = map; - methodmap_last = map; - } else { - methodmap_last->next = map; - methodmap_last = map; - } -} - -methodmap_t *methodmap_find_by_tag(int tag) -{ - methodmap_t *ptr = methodmap_first; - for (; ptr; ptr = ptr->next) { - if (ptr->tag == tag) - return ptr; - } - return NULL; -} - -methodmap_t *methodmap_find_by_name(const char *name) -{ - int tag = pc_findtag(name); - if (tag == -1) - return NULL; - return methodmap_find_by_tag(tag); -} - -methodmap_method_t *methodmap_find_method(methodmap_t *map, const char *name) -{ - size_t i; - for (i = 0; i < map->nummethods; i++) { - if (strcmp(map->methods[i]->name, name) == 0) - return map->methods[i]; - } - if (map->parent) - return methodmap_find_method(map->parent, name); - return NULL; -} - -void methodmaps_free() -{ - methodmap_t *ptr = methodmap_first; - while (ptr) { - methodmap_t *next = ptr->next; - for (size_t i = 0; i < ptr->nummethods; i++) - free(ptr->methods[i]); - free(ptr->methods); - free(ptr); - ptr = next; - } - methodmap_first = NULL; - methodmap_last = NULL; -} - -LayoutSpec deduce_layout_spec_by_tag(int tag) -{ - symbol *sym; - const char *name; - methodmap_t *map; - if ((map = methodmap_find_by_tag(tag)) != NULL) - return map->spec; - if (tag & FUNCTAG) - return Layout_FuncTag; - - name = pc_tagname(tag); - if (pstructs_find(name)) - return Layout_PawnStruct; - if ((sym = findglb(name, sGLOBAL)) != NULL) - return Layout_Enum; - - return Layout_None; -} - -LayoutSpec deduce_layout_spec_by_name(const char *name) -{ - symbol *sym; - methodmap_t *map; - int tag = pc_findtag(name); - if (tag != -1 && (tag & FUNCTAG)) - return Layout_FuncTag; - if (pstructs_find(name)) - return Layout_PawnStruct; - if ((map = methodmap_find_by_name(name)) != NULL) - return map->spec; - if ((sym = findglb(name, sGLOBAL)) != NULL) - return Layout_Enum; - - return Layout_None; -} - -const char *layout_spec_name(LayoutSpec spec) -{ - switch (spec) { - case Layout_None: - return ""; - case Layout_Enum: - return "enum"; - case Layout_FuncTag: - return "functag"; - case Layout_PawnStruct: - return "deprecated-struct"; - case Layout_MethodMap: - return "methodmap"; - case Layout_Class: - return "class"; - } - return ""; -} - -int can_redef_layout_spec(LayoutSpec def1, LayoutSpec def2) -{ - // Normalize the ordering, since these checks are symmetrical. - if (def1 > def2) { - LayoutSpec temp = def2; - def2 = def1; - def1 = temp; - } - - switch (def1) { - case Layout_None: - return TRUE; - case Layout_Enum: - if (def2 == Layout_Enum || def2 == Layout_FuncTag) - return TRUE; - return def2 == Layout_MethodMap; - case Layout_FuncTag: - return def2 == Layout_Enum || def2 == Layout_FuncTag; - case Layout_PawnStruct: - case Layout_MethodMap: - return FALSE; - case Layout_Class: - return FALSE; - } - return FALSE; -} - -size_t UTIL_Format(char *buffer, size_t maxlength, const char *fmt, ...) -{ - va_list ap; - - va_start(ap, fmt); - size_t len = vsnprintf(buffer, maxlength, fmt, ap); - va_end(ap); - - if (len >= maxlength) { - buffer[maxlength - 1] = '\0'; - return maxlength - 1; - } - return len; -} diff --git a/sourcepawn/compiler/sctracker.h b/sourcepawn/compiler/sctracker.h deleted file mode 100644 index 27f44ecc..00000000 --- a/sourcepawn/compiler/sctracker.h +++ /dev/null @@ -1,189 +0,0 @@ -/* vim: set sts=2 ts=8 sw=2 tw=99 et: */ -#ifndef _INCLUDE_SOURCEPAWN_COMPILER_TRACKER_H_ -#define _INCLUDE_SOURCEPAWN_COMPILER_TRACKER_H_ - -#define MEMUSE_STATIC 0 -#define MEMUSE_DYNAMIC 1 - -typedef struct memuse_s { - int type; /* MEMUSE_STATIC or MEMUSE_DYNAMIC */ - int size; /* size of array for static (0 for dynamic) */ - struct memuse_s *prev; /* previous block on the list */ -} memuse_t; - -typedef struct memuse_list_s { - struct memuse_list_s *prev; /* last used list */ - int list_id; - memuse_t *head; /* head of the current list */ -} memuse_list_t; - -typedef struct funcarg_s -{ - int tagcount; - int tags[sTAGS_MAX]; - int dimcount; - int dims[sDIMEN_MAX]; - int ident; - int fconst; - int ommittable; -} funcarg_t; - -typedef struct functag_s -{ - int ret_tag; - int usage; - int argcount; - int ommittable; - funcarg_t args[sARGS_MAX]; - struct functag_s *next; -} functag_t; - -typedef struct funcenum_s -{ - int tag; - char name[METHOD_NAMEMAX+1]; - functag_t *first; - functag_t *last; - struct funcenum_s *next; -} funcenum_t; - -typedef struct structarg_s -{ - int tag; - int dimcount; - int dims[sDIMEN_MAX]; - char name[sNAMEMAX+1]; - int fconst; - int ident; - unsigned int offs; - int index; -} structarg_t; - -typedef struct pstruct_s -{ - int argcount; - char name[sNAMEMAX+1]; - structarg_t **args; - struct pstruct_s *next; -} pstruct_t; - -// The ordering of these definitions should be preserved for -// can_redef_layout_spec(). -typedef enum LayoutSpec_t -{ - Layout_None, - Layout_Enum, - Layout_FuncTag, - Layout_PawnStruct, - Layout_MethodMap, - Layout_Class -} LayoutSpec; - -typedef struct methodmap_method_s -{ - char name[METHOD_NAMEMAX + 1]; - symbol *target; - symbol *getter; - symbol *setter; - bool is_static; - - int property_tag() const { - assert(getter || setter); - if (getter) - return getter->tag; - arginfo *thisp = &setter->dim.arglist[0]; - if (thisp->ident == 0) - return pc_tag_void; - arginfo *valp = &setter->dim.arglist[1]; - if (valp->ident != iVARIABLE || valp->numtags != 1) - return pc_tag_void; - return valp->tags[0]; - } -} methodmap_method_t; - -struct methodmap_t -{ - methodmap_t *next; - methodmap_t *parent; - int tag; - int nullable; - LayoutSpec spec; - char name[sNAMEMAX+1]; - methodmap_method_t **methods; - size_t nummethods; - - // Shortcut. - methodmap_method_t *dtor; - methodmap_method_t *ctor; -}; - -/** - * Pawn Structs - */ -pstruct_t *pstructs_add(const char *name); -void pstructs_free(); -pstruct_t *pstructs_find(const char *name); -structarg_t *pstructs_addarg(pstruct_t *pstruct, const structarg_t *arg); -structarg_t *pstructs_getarg(pstruct_t *pstruct, const char *member); - -/** - * Function enumeration tags - */ -void funcenums_free(); -funcenum_t *funcenums_add(const char *name); -funcenum_t *funcenums_find_by_tag(int tag); -functag_t *functags_add(funcenum_t *en, functag_t *src); -funcenum_t *funcenum_for_symbol(symbol *sym); -functag_t *functag_find_intrinsic(int tag); - -/** - * Given a name or tag, find any extra weirdness it has associated with it. - */ -LayoutSpec deduce_layout_spec_by_tag(int tag); -LayoutSpec deduce_layout_spec_by_name(const char *name); -const char *layout_spec_name(LayoutSpec spec); -int can_redef_layout_spec(LayoutSpec olddef, LayoutSpec newdef); - -/** - * Heap functions - */ -void pushheaplist(); -memuse_list_t *popsaveheaplist(); -void popheaplist(); -int markheap(int type, int size); - -/** - * Stack functions - */ -void pushstacklist(); -void popstacklist(int codegen); -int markstack(int type, int size); -/** - * Generates code to free mem usage, but does not pop the list. - * This is used for code like dobreak()/docont()/doreturn(). - * stop_id is the list at which to stop generating. - */ -void genstackfree(int stop_id); -void genheapfree(int stop_id); - -/** - * Resets a mem list by freeing everything - */ -void resetstacklist(); -void resetheaplist(); - -/** - * Method maps. - */ -void methodmap_add(methodmap_t *map); -methodmap_t *methodmap_find_by_tag(int tag); -methodmap_t *methodmap_find_by_name(const char *name); -methodmap_method_t *methodmap_find_method(methodmap_t *map, const char *name); -void methodmaps_free(); - -extern memuse_list_t *heapusage; -extern memuse_list_t *stackusage; - -size_t UTIL_Format(char *buffer, size_t maxlength, const char *fmt, ...); - -#endif //_INCLUDE_SOURCEPAWN_COMPILER_TRACKER_H_ diff --git a/sourcepawn/compiler/scvars.cpp b/sourcepawn/compiler/scvars.cpp deleted file mode 100644 index 3f1a5131..00000000 --- a/sourcepawn/compiler/scvars.cpp +++ /dev/null @@ -1,120 +0,0 @@ -/* Pawn compiler - * - * Global (cross-module) variables. - * - * Copyright (c) ITB CompuPhase, 1997-2006 - * - * This software is provided "as-is", without any express or implied warranty. - * In no event will the authors be held liable for any damages arising from - * the use of this software. - * - * Permission is granted to anyone to use this software for any purpose, - * including commercial applications, and to alter it and redistribute it - * freely, subject to the following restrictions: - * - * 1. The origin of this software must not be misrepresented; you must not - * claim that you wrote the original software. If you use this software in - * a product, an acknowledgment in the product documentation would be - * appreciated but is not required. - * 2. Altered source versions must be plainly marked as such, and must not be - * misrepresented as being the original software. - * 3. This notice may not be removed or altered from any source distribution. - * - * Version: $Id$ - */ -#include -#include /* for _MAX_PATH */ -#include "sc.h" -#include "sp_symhash.h" - -/* global variables - * - * All global variables that are shared amongst the compiler files are - * declared here. - */ -symbol loctab; /* local symbol table */ -symbol glbtab; /* global symbol table */ -cell *litq; /* the literal queue */ -unsigned char pline[sLINEMAX+1]; /* the line read from the input file */ -const unsigned char *lptr; /* points to the current position in "pline" */ -constvalue tagname_tab = { NULL, "", 0, 0}; /* tagname table */ -constvalue libname_tab = { NULL, "", 0, 0}; /* library table (#pragma library "..." syntax) */ -constvalue *curlibrary = NULL; /* current library */ -int pc_addlibtable = TRUE; /* is the library table added to the AMX file? */ -symbol *curfunc; /* pointer to current function */ -char *inpfname; /* pointer to name of the file currently read from */ -char outfname[_MAX_PATH]; /* intermediate (assembler) file name */ -char binfname[_MAX_PATH]; /* binary file name */ -char errfname[_MAX_PATH]; /* error file name */ -char sc_ctrlchar = CTRL_CHAR; /* the control character (or escape character)*/ -char sc_ctrlchar_org = CTRL_CHAR;/* the default control character */ -int litidx = 0; /* index to literal table */ -int litmax = sDEF_LITMAX; /* current size of the literal table */ -int stgidx = 0; /* index to the staging buffer */ -int sc_labnum = 0; /* number of (internal) labels */ -int staging = 0; /* true if staging output */ -cell declared = 0; /* number of local cells declared */ -cell glb_declared=0; /* number of global cells declared */ -cell code_idx = 0; /* number of bytes with generated code */ -int ntv_funcid= 0; /* incremental number of native function */ -int errnum = 0; /* number of errors */ -int warnnum = 0; /* number of warnings */ -int sc_debug = sCHKBOUNDS; /* by default: bounds checking+assertions */ -int sc_packstr= FALSE; /* strings are packed by default? */ -int sc_asmfile= FALSE; /* create .ASM file? */ -int sc_listing= FALSE; /* create .LST file? */ -int sc_compress=TRUE; /* compress bytecode? */ -int sc_needsemicolon=TRUE;/* semicolon required to terminate expressions? */ -int sc_dataalign=sizeof(cell);/* data alignment value */ -int sc_alignnext=FALSE; /* must frame of the next function be aligned? */ -int pc_docexpr=FALSE; /* must expression be attached to documentation comment? */ -int curseg = 0; /* 1 if currently parsing CODE, 2 if parsing DATA */ -cell pc_stksize=sDEF_AMXSTACK;/* default stack size */ -cell pc_amxlimit=0; /* default abstract machine size limit = none */ -cell pc_amxram=0; /* default abstract machine data size limit = none */ -int freading = FALSE; /* Is there an input file ready for reading? */ -int fline = 0; /* the line number in the current file */ -short fnumber = 0; /* the file number in the file table (debugging) */ -short fcurrent= 0; /* current file being processed (debugging) */ -short sc_intest=FALSE; /* true if inside a test */ -int sideeffect= 0; /* true if an expression causes a side-effect */ -int stmtindent= 0; /* current indent of the statement */ -int indent_nowarn=FALSE;/* skip warning "217 loose indentation" */ -int sc_tabsize=8; /* number of spaces that a TAB represents */ -short sc_allowtags=TRUE; /* allow/detect tagnames in lex() */ -int sc_status; /* read/write status */ -int sc_err_status; -int sc_rationaltag=0; /* tag for rational numbers */ -int rational_digits=0; /* number of fractional digits */ -int sc_allowproccall=0; /* allow/detect tagnames in lex() */ -short sc_is_utf8=FALSE; /* is this source file in UTF-8 encoding */ -char *pc_deprecate=NULL;/* if non-null, mark next declaration as deprecated */ -int sc_curstates=0; /* ID of the current state list */ -int pc_optimize=sOPTIMIZE_NOMACRO; /* (peephole) optimization level */ -int pc_memflags=0; /* special flags for the stack/heap usage */ -int sc_showincludes=0; /* show include files */ -int sc_require_newdecls=0; /* Require new-style declarations */ -bool sc_warnings_are_errors=false; - -constvalue sc_automaton_tab = { NULL, "", 0, 0}; /* automaton table */ -constvalue sc_state_tab = { NULL, "", 0, 0}; /* state table */ - -void *inpf = NULL; /* file read from (source or include) */ -void *inpf_org= NULL; /* main source file */ -void *outf = NULL; /* (intermediate) text file written to */ - -jmp_buf errbuf; - -HashTable *sp_Globals = NULL; - -#if !defined SC_LIGHT - int sc_makereport=FALSE; /* generate a cross-reference report */ -#endif - -#if defined __WATCOMC__ && !defined NDEBUG - /* Watcom's CVPACK dislikes .OBJ files without functions */ - static int dummyfunc(void) - { - return 0; - } -#endif diff --git a/sourcepawn/compiler/smx-builder.cpp b/sourcepawn/compiler/smx-builder.cpp deleted file mode 100644 index d33f0330..00000000 --- a/sourcepawn/compiler/smx-builder.cpp +++ /dev/null @@ -1,111 +0,0 @@ -// vim: set sts=2 ts=8 sw=2 tw=99 et: -// -// Copyright (C) 2012-2014 David Anderson -// -// This file is part of SourcePawn. -// -// SourcePawn is free software: you can redistribute it and/or modify it under -// the terms of the GNU General Public License as published by the Free -// Software Foundation, either version 3 of the License, or (at your option) -// any later version. -// -// SourcePawn is distributed in the hope that it will be useful, but WITHOUT ANY -// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -// FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. -// -// You should have received a copy of the GNU General Public License along with -// SourcePawn. If not, see http://www.gnu.org/licenses/. -#include "smx-builder.h" - -using namespace ke; -using namespace sp; - -SmxBuilder::SmxBuilder() -{ -} - -bool -SmxBuilder::write(ISmxBuffer *buf) -{ - sp_file_hdr_t header; - header.magic = SmxConsts::FILE_MAGIC; - header.version = SmxConsts::SP1_VERSION_1_1; - header.compression = SmxConsts::FILE_COMPRESSION_NONE; - - header.disksize = sizeof(header) + - sizeof(sp_file_section_t) * sections_.length(); - - // Note that |dataoffs| here is just to mimic what it would be in earlier - // versions of Pawn. Its value does not actually matter per the SMX spec, - // aside from having to be >= sizeof(sp_file_hdr_t). Here, we hint that - // only the region after the section list and names should be compressed. - header.dataoffs = header.disksize; - - size_t current_string_offset = 0; - for (size_t i = 0; i < sections_.length(); i++) { - Ref section = sections_[i]; - header.disksize += section->length(); - current_string_offset += section->name().length() + 1; - } - header.disksize += current_string_offset; - header.dataoffs += current_string_offset; - - header.imagesize = header.disksize; - header.sections = sections_.length(); - - // We put the string table after the sections table. - header.stringtab = sizeof(header) + sizeof(sp_file_section_t) * sections_.length(); - - if (!buf->write(&header, sizeof(header))) - return false; - - size_t current_offset = sizeof(header); - size_t current_data_offset = header.stringtab + current_string_offset; - current_string_offset = 0; - for (size_t i = 0; i < sections_.length(); i++) { - sp_file_section_t s; - s.nameoffs = current_string_offset; - s.dataoffs = current_data_offset; - s.size = sections_[i]->length(); - if (!buf->write(&s, sizeof(s))) - return false; - - current_offset += sizeof(s); - current_data_offset += s.size; - current_string_offset += sections_[i]->name().length() + 1; - } - assert(buf->pos() == current_offset); - assert(current_offset == header.stringtab); - - for (size_t i = 0; i < sections_.length(); i++) { - const AString &name = sections_[i]->name(); - if (!buf->write(name.chars(), name.length() + 1)) - return false; - } - current_offset += current_string_offset; - - assert(buf->pos() == current_offset); - - for (size_t i = 0; i < sections_.length(); i++) { - if (!sections_[i]->write(buf)) - return false; - current_offset += sections_[i]->length(); - } - - assert(buf->pos() == current_offset); - assert(current_offset == header.disksize); - - return true; -} - -bool -SmxNameTable::write(ISmxBuffer *buf) -{ - for (size_t i = 0; i < names_.length(); i++) { - Atom *str = names_[i]; - if (!buf->write(str->chars(), str->length() + 1)) - return false; - } - return true; -} - diff --git a/sourcepawn/compiler/smx-builder.h b/sourcepawn/compiler/smx-builder.h deleted file mode 100644 index 22295bab..00000000 --- a/sourcepawn/compiler/smx-builder.h +++ /dev/null @@ -1,217 +0,0 @@ -// vim: set sts=2 ts=8 sw=2 tw=99 et: -// -// Copyright (C) 2012-2014 AlliedModders LLC, David Anderson -// -// This file is part of SourcePawn. -// -// SourcePawn is free software: you can redistribute it and/or modify it under -// the terms of the GNU General Public License as published by the Free -// Software Foundation, either version 3 of the License, or (at your option) -// any later version. -// -// SourcePawn is distributed in the hope that it will be useful, but WITHOUT ANY -// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -// FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. -// -// You should have received a copy of the GNU General Public License along with -// SourcePawn. If not, see http://www.gnu.org/licenses/. -#ifndef _include_spcomp2_smx_builder_h_ -#define _include_spcomp2_smx_builder_h_ - -#include -#include -#include -#include -#include -#include "string-pool.h" -#include "memory-buffer.h" - -namespace ke { - -// An SmxSection is a named blob of data. -class SmxSection : public Refcounted -{ - public: - SmxSection(const char *name) - : name_(name) - { - } - - virtual bool write(ISmxBuffer *buf) = 0; - virtual size_t length() const = 0; - - const AString &name() const { - return name_; - } - - private: - AString name_; -}; - -// An SmxBlobSection is a section that has some kind of header structure -// (specified as a template parameter), and then an arbitrary run of bytes -// immediately after. -template -class SmxBlobSection : public SmxSection -{ - public: - SmxBlobSection(const char *name) - : SmxSection(name), - extra_(nullptr), - extra_len_(0) - { - memset(&t_, 0, sizeof(t_)); - } - - T &header() { - return t_; - } - void setBlob(uint8_t *blob, size_t len) { - extra_ = blob; - extra_len_ = len; - } - bool write(ISmxBuffer *buf) KE_OVERRIDE { - if (!buf->write(&t_, sizeof(t_))) - return false; - if (!extra_len_) - return true; - return buf->write(extra_, extra_len_); - } - size_t length() const KE_OVERRIDE { - return sizeof(t_) + extra_len_; - } - - private: - T t_; - uint8_t *extra_; - size_t extra_len_; -}; - -// An SmxBlobSection without headers. -template <> -class SmxBlobSection : public SmxSection -{ - public: - SmxBlobSection(const char *name) - : SmxSection(name) - { - } - - void add(void *bytes, size_t len) { - buffer_.write(bytes, len); - } - bool write(ISmxBuffer *buf) KE_OVERRIDE { - return buf->write(buffer_.bytes(), buffer_.size()); - } - size_t length() const KE_OVERRIDE { - return buffer_.size(); - } - - private: - MemoryBuffer buffer_; -}; - -// An SmxListSection is a section that is a simple table of uniformly-sized -// structures. It has no header of its own. -template -class SmxListSection : public SmxSection -{ - public: - SmxListSection(const char *name) - : SmxSection(name) - { - } - - void append(const T &t) { - list_.append(t); - } - T &add() { - list_.append(T()); - return list_.back(); - } - void add(const T &t) { - list_.append(t); - } - bool write(ISmxBuffer *buf) KE_OVERRIDE { - return buf->write(list_.buffer(), list_.length() * sizeof(T)); - } - size_t length() const KE_OVERRIDE { - return count() * sizeof(T); - } - size_t count() const { - return list_.length(); - } - - private: - Vector list_; -}; - -// A name table is a blob of zero-terminated strings. Strings are entered -// into the table as atoms, so duplicate stings are not emitted. -class SmxNameTable : public SmxSection -{ - public: - SmxNameTable(const char *name) - : SmxSection(name), - buffer_size_(0) - { - name_table_.init(64); - } - - uint32_t add(StringPool &pool, const char *str) { - return add(pool.add(str)); - } - - uint32_t add(Atom *str) { - NameTable::Insert i = name_table_.findForAdd(str); - if (i.found()) - return i->value; - - assert(IsUint32AddSafe(buffer_size_, str->length() + 1)); - - uint32_t index = buffer_size_; - name_table_.add(i, str, index); - names_.append(str); - buffer_size_ += str->length() + 1; - return index; - } - - bool write(ISmxBuffer *buf) KE_OVERRIDE; - size_t length() const KE_OVERRIDE { - return buffer_size_; - } - - private: - struct HashPolicy { - static uint32_t hash(Atom *str) { - return HashPointer(str); - } - static bool matches(Atom *a, Atom *b) { - return a == b; - } - }; - typedef HashMap NameTable; - - NameTable name_table_; - Vector names_; - uint32_t buffer_size_; -}; - -class SmxBuilder -{ - public: - SmxBuilder(); - - bool write(ISmxBuffer *buf); - - void add(const Ref §ion) { - sections_.append(section); - } - - private: - Vector> sections_; -}; - -} // namespace ke - -#endif // _include_spcomp2_smx_builder_h_ diff --git a/sourcepawn/compiler/sp_symhash.cpp b/sourcepawn/compiler/sp_symhash.cpp deleted file mode 100644 index 1b50b0ae..00000000 --- a/sourcepawn/compiler/sp_symhash.cpp +++ /dev/null @@ -1,129 +0,0 @@ -// vim: set ts=8 sts=2 sw=2 tw=99 et: -#include -#include -#include -#include "sc.h" -#include "sp_symhash.h" -#include - -struct NameAndScope -{ - const char *name; - int fnumber; - int *cmptag; - mutable symbol *matched; - mutable int count; - - NameAndScope(const char *name, int fnumber, int *cmptag) - : name(name), - fnumber(fnumber), - cmptag(cmptag), - matched(nullptr), - count(0) - { - } -}; - -struct SymbolHashPolicy -{ - typedef symbol *Payload; - - // Everything with the same name has the same hash, because the compiler - // wants to know two names that have the same tag for some reason. Even - // so, we can't be that accurate, since we might match the right symbol - // very early. - static uint32_t hash(const NameAndScope &key) { - return ke::HashCharSequence(key.name, strlen(key.name)); - } - static uint32_t hash(const symbol *s) { - return ke::HashCharSequence(s->name, strlen(s->name)); - } - - static bool matches(const NameAndScope &key, symbol *sym) { - if (sym->parent && sym->ident != iCONSTEXPR) - return false; - if (sym->fnumber >= 0 && sym->fnumber != key.fnumber) - return false; - if (strcmp(key.name, sym->name) != 0) - return false; - if (key.cmptag) { - key.count++; - key.matched = sym; - if (*key.cmptag != sym->tag) - return false; - } - return true; - } - static bool matches(const symbol *key, symbol *sym) { - return key == sym; - } -}; - -struct HashTable : public ke::HashTable -{ -}; - -uint32_t -NameHash(const char *str) -{ - return ke::HashCharSequence(str, strlen(str)); -} - -HashTable *NewHashTable() -{ - HashTable *ht = new HashTable(); - if (!ht->init()) { - delete ht; - return nullptr; - } - return ht; -} - -void -DestroyHashTable(HashTable *ht) -{ - delete ht; -} - -symbol * -FindTaggedInHashTable(HashTable *ht, const char *name, int fnumber, int *cmptag) -{ - NameAndScope nas(name, fnumber, cmptag); - HashTable::Result r = ht->find(nas); - if (!r.found()) { - if (nas.matched) { - *cmptag = nas.count; - return nas.matched; - } - return nullptr; - } - - *cmptag = 1; - return *r; -} - -symbol * -FindInHashTable(HashTable *ht, const char *name, int fnumber) -{ - NameAndScope nas(name, fnumber, nullptr); - HashTable::Result r = ht->find(nas); - if (!r.found()) - return nullptr; - return *r; -} - -void -AddToHashTable(HashTable *ht, symbol *sym) -{ - HashTable::Insert i = ht->findForAdd(sym); - assert(!i.found()); - ht->add(i, sym); -} - -void -RemoveFromHashTable(HashTable *ht, symbol *sym) -{ - HashTable::Result r = ht->find(sym); - assert(r.found()); - ht->remove(r); -} diff --git a/sourcepawn/compiler/sp_symhash.h b/sourcepawn/compiler/sp_symhash.h deleted file mode 100644 index 3617368f..00000000 --- a/sourcepawn/compiler/sp_symhash.h +++ /dev/null @@ -1,18 +0,0 @@ -/* vim: set ts=4 sw=4 tw=99 et: */ -#ifndef _INCLUDE_SPCOMP_SYMHASH_H_ -#define _INCLUDE_SPCOMP_SYMHASH_H_ - -uint32_t NameHash(const char *str); - -struct HashTable; - -HashTable *NewHashTable(); -void DestroyHashTable(HashTable *ht); -void AddToHashTable(HashTable *ht, symbol *sym); -void RemoveFromHashTable(HashTable *ht, symbol *sym); -symbol *FindInHashTable(HashTable *ht, const char *name, int fnumber); -symbol *FindTaggedInHashTable(HashTable *ht, const char *name, int fnumber, - int *cmptag); - -#endif /* _INCLUDE_SPCOMP_SYMHASH_H_ */ - diff --git a/sourcepawn/compiler/string-pool.h b/sourcepawn/compiler/string-pool.h deleted file mode 100644 index 63ef10e0..00000000 --- a/sourcepawn/compiler/string-pool.h +++ /dev/null @@ -1,146 +0,0 @@ -/* vim: set ts=2 sw=2 tw=99 et: - * - * Copyright (C) 2012-2014 AlliedModders LLC, David Anderson - * - * This file is part of SourcePawn. - * - * SourcePawn is free software: you can redistribute it and/or modify it under - * the terms of the GNU General Public License as published by the Free - * Software Foundation, either version 3 of the License, or (at your option) - * any later version. - * - * SourcePawn is distributed in the hope that it will be useful, but WITHOUT ANY - * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS - * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License along with - * SourcePawn. If not, see http://www.gnu.org/licenses/. - */ -#ifndef _include_jitcraft_string_pool_h_ -#define _include_jitcraft_string_pool_h_ - -// string-pool is a collection of helpers to atomize/internalize strings. The -// StringPool class provides Atom objects which can be used for efficiently -// handling string sets or dictionaries. - -#include -#include -#include - -namespace ke { - -// An Atom is a string that has a unique instance. That is, any Atom("a") is -// guaranteed to be pointer-equivalent to another Atom("a"), as long as they -// originated from the same StringPool. -class Atom -{ - friend class StringPool; - - private: - Atom(const char *str, size_t len) - : str_(str, len) - { - } - - public: - size_t length() const { - return str_.length(); - } - const char *chars() const { - return str_.chars(); - } - - private: - AString str_; -}; - -// Helper class to use as a key for hash table lookups. -class CharsAndLength -{ - public: - CharsAndLength() - : str_(nullptr), - length_(0) - { - } - - CharsAndLength(const char *str, size_t length) - : str_(str), - length_(length) - { - } - - const char *str() const { - return str_; - } - size_t length() const { - return length_; - } - - private: - const char *str_; - size_t length_; -}; - -// Atom dictionary. -class StringPool -{ - public: - StringPool() - : table_(SystemAllocatorPolicy()) - { - init(); - } - - ~StringPool() - { - if (!table_.elements()) - return; - for (Table::iterator i(&table_); !i.empty(); i.next()) - delete *i; - } - - bool init() { - return table_.init(256); - } - - Atom *add(const char *str, size_t length) { - CharsAndLength chars(str, length); - Table::Insert p = table_.findForAdd(chars); - if (!p.found() && !table_.add(p, new Atom(str, length))) - return nullptr; - return *p; - } - - Atom *add(const char *str) { - return add(str, strlen(str)); - } - - private: - struct Policy { - typedef Atom *Payload; - - static uint32_t hash(const char *key) { - return HashCharSequence(key, strlen(key)); - } - - static uint32_t hash(const CharsAndLength &key) { - return HashCharSequence(key.str(), key.length()); - } - - static bool matches(const CharsAndLength &key, const Payload &e) { - if (key.length() != e->length()) - return false; - return strcmp(key.str(), e->chars()) == 0; - } - }; - - typedef HashTable Table; - - private: - Table table_; -}; - -} // namespace ke - -#endif // _include_jitcraft_string_pool_h_ diff --git a/sourcepawn/compiler/tests/disabled/fail-mix-methodmap-and-class-1.sp b/sourcepawn/compiler/tests/disabled/fail-mix-methodmap-and-class-1.sp deleted file mode 100644 index d26a946e..00000000 --- a/sourcepawn/compiler/tests/disabled/fail-mix-methodmap-and-class-1.sp +++ /dev/null @@ -1,11 +0,0 @@ -methodmap Y -{ -}; - -class X < Y -{ -}; - -public main() -{ -} diff --git a/sourcepawn/compiler/tests/disabled/fail-mix-methodmap-and-class-1.txt b/sourcepawn/compiler/tests/disabled/fail-mix-methodmap-and-class-1.txt deleted file mode 100644 index 1d0676ce..00000000 --- a/sourcepawn/compiler/tests/disabled/fail-mix-methodmap-and-class-1.txt +++ /dev/null @@ -1 +0,0 @@ -cannot mix methodmaps and classes with inheritance diff --git a/sourcepawn/compiler/tests/disabled/fail-mix-methodmap-and-class-2.sp b/sourcepawn/compiler/tests/disabled/fail-mix-methodmap-and-class-2.sp deleted file mode 100644 index fee89626..00000000 --- a/sourcepawn/compiler/tests/disabled/fail-mix-methodmap-and-class-2.sp +++ /dev/null @@ -1,11 +0,0 @@ -class Y -{ -}; - -methodmap X < Y -{ -}; - -public main() -{ -} diff --git a/sourcepawn/compiler/tests/disabled/fail-mix-methodmap-and-class-2.txt b/sourcepawn/compiler/tests/disabled/fail-mix-methodmap-and-class-2.txt deleted file mode 100644 index 1d0676ce..00000000 --- a/sourcepawn/compiler/tests/disabled/fail-mix-methodmap-and-class-2.txt +++ /dev/null @@ -1 +0,0 @@ -cannot mix methodmaps and classes with inheritance diff --git a/sourcepawn/compiler/tests/disabled/fail-none-to-obj.sp b/sourcepawn/compiler/tests/disabled/fail-none-to-obj.sp deleted file mode 100644 index 21ab11b7..00000000 --- a/sourcepawn/compiler/tests/disabled/fail-none-to-obj.sp +++ /dev/null @@ -1,13 +0,0 @@ -class X -{ -}; - -f(X:x) -{ - return 3 -} - -public main() -{ - return f(2); -} diff --git a/sourcepawn/compiler/tests/disabled/fail-none-to-obj.txt b/sourcepawn/compiler/tests/disabled/fail-none-to-obj.txt deleted file mode 100644 index 4523d543..00000000 --- a/sourcepawn/compiler/tests/disabled/fail-none-to-obj.txt +++ /dev/null @@ -1 +0,0 @@ -cannot coerce non-object type int to object type X diff --git a/sourcepawn/compiler/tests/disabled/fail-obj-to-any.sp b/sourcepawn/compiler/tests/disabled/fail-obj-to-any.sp deleted file mode 100644 index 6545cb49..00000000 --- a/sourcepawn/compiler/tests/disabled/fail-obj-to-any.sp +++ /dev/null @@ -1,14 +0,0 @@ -class X -{ -}; - -f(any:x) -{ - return 3 -} - -public main() -{ - new X:x; - return f(x); -} diff --git a/sourcepawn/compiler/tests/disabled/fail-obj-to-any.txt b/sourcepawn/compiler/tests/disabled/fail-obj-to-any.txt deleted file mode 100644 index 69c73982..00000000 --- a/sourcepawn/compiler/tests/disabled/fail-obj-to-any.txt +++ /dev/null @@ -1 +0,0 @@ -cannot coerce object type X to non-object type any diff --git a/sourcepawn/compiler/tests/disabled/fail-obj-to-multitag.sp b/sourcepawn/compiler/tests/disabled/fail-obj-to-multitag.sp deleted file mode 100644 index 4e92090a..00000000 --- a/sourcepawn/compiler/tests/disabled/fail-obj-to-multitag.sp +++ /dev/null @@ -1,14 +0,0 @@ -class X -{ -}; - -f({X,Float}:x) -{ - return 3 -} - -public main() -{ - new X:x; - return f(x); -} diff --git a/sourcepawn/compiler/tests/disabled/fail-obj-to-multitag.txt b/sourcepawn/compiler/tests/disabled/fail-obj-to-multitag.txt deleted file mode 100644 index 46c7f41f..00000000 --- a/sourcepawn/compiler/tests/disabled/fail-obj-to-multitag.txt +++ /dev/null @@ -1 +0,0 @@ -cannot use an object in a multi-tag selector diff --git a/sourcepawn/compiler/tests/disabled/fail-obj-to-none.sp b/sourcepawn/compiler/tests/disabled/fail-obj-to-none.sp deleted file mode 100644 index 85045712..00000000 --- a/sourcepawn/compiler/tests/disabled/fail-obj-to-none.sp +++ /dev/null @@ -1,14 +0,0 @@ -class X -{ -}; - -f(x) -{ - return 3 -} - -public main() -{ - new X:x; - return f(x); -} diff --git a/sourcepawn/compiler/tests/disabled/fail-obj-to-none.txt b/sourcepawn/compiler/tests/disabled/fail-obj-to-none.txt deleted file mode 100644 index 20ceed6f..00000000 --- a/sourcepawn/compiler/tests/disabled/fail-obj-to-none.txt +++ /dev/null @@ -1 +0,0 @@ -cannot coerce object type X to non-object type int diff --git a/sourcepawn/compiler/tests/disabled/fail-obj-to-varargs.sp b/sourcepawn/compiler/tests/disabled/fail-obj-to-varargs.sp deleted file mode 100644 index ba0d8014..00000000 --- a/sourcepawn/compiler/tests/disabled/fail-obj-to-varargs.sp +++ /dev/null @@ -1,14 +0,0 @@ -class X -{ -}; - -f(...) -{ - return 3 -} - -public main() -{ - new X:x; - return f(x); -} diff --git a/sourcepawn/compiler/tests/disabled/fail-obj-to-varargs.txt b/sourcepawn/compiler/tests/disabled/fail-obj-to-varargs.txt deleted file mode 100644 index 20ceed6f..00000000 --- a/sourcepawn/compiler/tests/disabled/fail-obj-to-varargs.txt +++ /dev/null @@ -1 +0,0 @@ -cannot coerce object type X to non-object type int diff --git a/sourcepawn/compiler/tests/disabled/fail-object-keyword-as-name.sp b/sourcepawn/compiler/tests/disabled/fail-object-keyword-as-name.sp deleted file mode 100644 index 756c2a69..00000000 --- a/sourcepawn/compiler/tests/disabled/fail-object-keyword-as-name.sp +++ /dev/null @@ -1,5 +0,0 @@ -public Action:SomeEvent( Handle:event, const String:name[], bool:dontBroadcast) -{ - // error 143: new-style declarations should not have "new" - new object = GetEventInt(event, "object"); -} diff --git a/sourcepawn/compiler/tests/disabled/fail-object-keyword-as-name.txt b/sourcepawn/compiler/tests/disabled/fail-object-keyword-as-name.txt deleted file mode 100644 index ed270926..00000000 --- a/sourcepawn/compiler/tests/disabled/fail-object-keyword-as-name.txt +++ /dev/null @@ -1 +0,0 @@ -(4) : error 157: 'object' is a reserved keyword diff --git a/sourcepawn/compiler/tests/disabled/fail-relabel-int-to-obj.sp b/sourcepawn/compiler/tests/disabled/fail-relabel-int-to-obj.sp deleted file mode 100644 index 0b238bdc..00000000 --- a/sourcepawn/compiler/tests/disabled/fail-relabel-int-to-obj.sp +++ /dev/null @@ -1,14 +0,0 @@ -class X -{ -}; - -f(X:x) -{ - return 3 -} - -public main() -{ - new x; - return f(X:x); -} diff --git a/sourcepawn/compiler/tests/disabled/fail-relabel-int-to-obj.txt b/sourcepawn/compiler/tests/disabled/fail-relabel-int-to-obj.txt deleted file mode 100644 index 4523d543..00000000 --- a/sourcepawn/compiler/tests/disabled/fail-relabel-int-to-obj.txt +++ /dev/null @@ -1 +0,0 @@ -cannot coerce non-object type int to object type X diff --git a/sourcepawn/compiler/tests/disabled/fail-relabel-obj-to-int.sp b/sourcepawn/compiler/tests/disabled/fail-relabel-obj-to-int.sp deleted file mode 100644 index 832774c3..00000000 --- a/sourcepawn/compiler/tests/disabled/fail-relabel-obj-to-int.sp +++ /dev/null @@ -1,14 +0,0 @@ -class X -{ -}; - -f(x) -{ - return 3 -} - -public main() -{ - new X:x; - return f(_:x); -} diff --git a/sourcepawn/compiler/tests/disabled/fail-relabel-obj-to-int.txt b/sourcepawn/compiler/tests/disabled/fail-relabel-obj-to-int.txt deleted file mode 100644 index 20ceed6f..00000000 --- a/sourcepawn/compiler/tests/disabled/fail-relabel-obj-to-int.txt +++ /dev/null @@ -1 +0,0 @@ -cannot coerce object type X to non-object type int diff --git a/sourcepawn/compiler/tests/fail-array-on-implicit-this.sp b/sourcepawn/compiler/tests/fail-array-on-implicit-this.sp deleted file mode 100644 index 820c4524..00000000 --- a/sourcepawn/compiler/tests/fail-array-on-implicit-this.sp +++ /dev/null @@ -1,9 +0,0 @@ -native CloseHandle(Handle:handle[]); - -methodmap Handle { - public Close() = CloseHandle; -}; - -public main() -{ -} diff --git a/sourcepawn/compiler/tests/fail-array-on-implicit-this.txt b/sourcepawn/compiler/tests/fail-array-on-implicit-this.txt deleted file mode 100644 index aedab634..00000000 --- a/sourcepawn/compiler/tests/fail-array-on-implicit-this.txt +++ /dev/null @@ -1 +0,0 @@ -method must have a first argument compatible with the methodmap type (Handle) diff --git a/sourcepawn/compiler/tests/fail-assign-null-to-any.sp b/sourcepawn/compiler/tests/fail-assign-null-to-any.sp deleted file mode 100644 index 16be5876..00000000 --- a/sourcepawn/compiler/tests/fail-assign-null-to-any.sp +++ /dev/null @@ -1,4 +0,0 @@ -Foo(any foo) {} -public Bar() { - Foo(null); -} diff --git a/sourcepawn/compiler/tests/fail-assign-null-to-any.txt b/sourcepawn/compiler/tests/fail-assign-null-to-any.txt deleted file mode 100644 index cb98bb52..00000000 --- a/sourcepawn/compiler/tests/fail-assign-null-to-any.txt +++ /dev/null @@ -1 +0,0 @@ -(3) : error 148: cannot assign null to a non-nullable type diff --git a/sourcepawn/compiler/tests/fail-assign-string-and-nonstring.sp b/sourcepawn/compiler/tests/fail-assign-string-and-nonstring.sp deleted file mode 100644 index d7f34615..00000000 --- a/sourcepawn/compiler/tests/fail-assign-string-and-nonstring.sp +++ /dev/null @@ -1,7 +0,0 @@ -public main() -{ - char x[40]; - any y[10]; - x = y; - y = x; -} diff --git a/sourcepawn/compiler/tests/fail-assign-string-and-nonstring.txt b/sourcepawn/compiler/tests/fail-assign-string-and-nonstring.txt deleted file mode 100644 index 102dad96..00000000 --- a/sourcepawn/compiler/tests/fail-assign-string-and-nonstring.txt +++ /dev/null @@ -1,2 +0,0 @@ -(5) : error 179: cannot assign char[] to any[], storage classes differ -(6) : error 179: cannot assign any[] to char[], storage classes differ diff --git a/sourcepawn/compiler/tests/fail-assign-to-this.sp b/sourcepawn/compiler/tests/fail-assign-to-this.sp deleted file mode 100644 index 2bd47b80..00000000 --- a/sourcepawn/compiler/tests/fail-assign-to-this.sp +++ /dev/null @@ -1,12 +0,0 @@ -methodmap Egg -{ - public void illegal(Egg x) { - this = x; - } -}; - -public main() -{ - Egg egg; - egg.illegal(egg); -} diff --git a/sourcepawn/compiler/tests/fail-assign-to-this.txt b/sourcepawn/compiler/tests/fail-assign-to-this.txt deleted file mode 100644 index 530c5065..00000000 --- a/sourcepawn/compiler/tests/fail-assign-to-this.txt +++ /dev/null @@ -1 +0,0 @@ -(4) : error 022: must be lvalue (non-constant) diff --git a/sourcepawn/compiler/tests/fail-bad-arg-decls.sp b/sourcepawn/compiler/tests/fail-bad-arg-decls.sp deleted file mode 100644 index cda0ec89..00000000 --- a/sourcepawn/compiler/tests/fail-bad-arg-decls.sp +++ /dev/null @@ -1,15 +0,0 @@ -stock A(int) -{ -} - -stock B(int[5] N) -{ -} - -stock C(int:N) -{ -} - -public main() -{ -} diff --git a/sourcepawn/compiler/tests/fail-bad-arg-decls.txt b/sourcepawn/compiler/tests/fail-bad-arg-decls.txt deleted file mode 100644 index f6404967..00000000 --- a/sourcepawn/compiler/tests/fail-bad-arg-decls.txt +++ /dev/null @@ -1,3 +0,0 @@ -(1) : error 001: expected token: "-identifier-", but found ")" -(5) : error 140: new-style array types cannot specify dimension sizes as part of their type -(9) : warning 238: 'int:' is an illegal cast; use view_as(expression) diff --git a/sourcepawn/compiler/tests/fail-bad-array-decls.sp b/sourcepawn/compiler/tests/fail-bad-array-decls.sp deleted file mode 100644 index 0a834b8f..00000000 --- a/sourcepawn/compiler/tests/fail-bad-array-decls.sp +++ /dev/null @@ -1,17 +0,0 @@ -int[] gInvalid = {1}; - -public OnPluginStart() -{ - int v = 10; - int invalid1[v]; - int[] invalid2 = {1}; - static int[] invalid3 = {1}; -} - -void invalid_arg1(int invalid[]) -{ -} - -void invalid_arg2(int[] invalid = {1, 2, 3}) -{ -} diff --git a/sourcepawn/compiler/tests/fail-bad-array-decls.txt b/sourcepawn/compiler/tests/fail-bad-array-decls.txt deleted file mode 100644 index f415a354..00000000 --- a/sourcepawn/compiler/tests/fail-bad-array-decls.txt +++ /dev/null @@ -1,7 +0,0 @@ -(1) : error 162: cannot create dynamic arrays in global scope - did you mean to create a fixed-length array with brackets after the variable name? -(6) : error 161: brackets after variable name indicate a fixed-size array, but a dynamic size was given - did you mean to use 'new int[size]' syntax? -(7) : error 160: brackets in between type and variable name indicate a dynamic-size array, but a fixed-size initializer was given -(8) : error 165: cannot create dynamic arrays in static scope - did you mean to create a fixed-length array with brackets after the variable name? -(11) : error 159: brackets after variable name indicate a fixed-size array, but size could not be determined - either specify sizes, an array initializer, or use dynamic syntax (such as 'char[] x') -(15) : error 160: brackets in between type and variable name indicate a dynamic-size array, but a fixed-size initializer was given - diff --git a/sourcepawn/compiler/tests/fail-bad-void.sp b/sourcepawn/compiler/tests/fail-bad-void.sp deleted file mode 100644 index 4e83660f..00000000 --- a/sourcepawn/compiler/tests/fail-bad-void.sp +++ /dev/null @@ -1,13 +0,0 @@ -void[] Bad1() -{ -} - -void Bad2; - -stock Bad3(void x) -{ -} - -public main() -{ -} diff --git a/sourcepawn/compiler/tests/fail-bad-void.txt b/sourcepawn/compiler/tests/fail-bad-void.txt deleted file mode 100644 index 7d5d07c8..00000000 --- a/sourcepawn/compiler/tests/fail-bad-void.txt +++ /dev/null @@ -1,3 +0,0 @@ -(1) : error 145: invalid type expression -(5) : error 144: void cannot be used as a variable type -(7) : error 144: void cannot be used as a variable type diff --git a/sourcepawn/compiler/tests/fail-call-non-static-on-type.sp b/sourcepawn/compiler/tests/fail-call-non-static-on-type.sp deleted file mode 100644 index ac6df284..00000000 --- a/sourcepawn/compiler/tests/fail-call-non-static-on-type.sp +++ /dev/null @@ -1,12 +0,0 @@ -native printnum(t); - -methodmap X -{ - public int GetThing() { - return 10; - } -} - -public main() { - printnum(X.GetThing()); -} diff --git a/sourcepawn/compiler/tests/fail-call-non-static-on-type.txt b/sourcepawn/compiler/tests/fail-call-non-static-on-type.txt deleted file mode 100644 index 42c312db..00000000 --- a/sourcepawn/compiler/tests/fail-call-non-static-on-type.txt +++ /dev/null @@ -1 +0,0 @@ -(11) : error 176: non-static method or property 'GetThing' must be called with a value of type 'X' diff --git a/sourcepawn/compiler/tests/fail-call-static-via-instance.sp b/sourcepawn/compiler/tests/fail-call-static-via-instance.sp deleted file mode 100644 index 24a16591..00000000 --- a/sourcepawn/compiler/tests/fail-call-static-via-instance.sp +++ /dev/null @@ -1,13 +0,0 @@ -native printnum(t); - -methodmap X -{ - public static int GetThing() { - return 10; - } -} - -public main() { - X x; - printnum(x.GetThing()); -} diff --git a/sourcepawn/compiler/tests/fail-call-static-via-instance.txt b/sourcepawn/compiler/tests/fail-call-static-via-instance.txt deleted file mode 100644 index 9a7dbc95..00000000 --- a/sourcepawn/compiler/tests/fail-call-static-via-instance.txt +++ /dev/null @@ -1 +0,0 @@ -(12) : error 177: static method 'GetThing' must be invoked via its type (try 'X.GetThing') diff --git a/sourcepawn/compiler/tests/fail-callback-returns-array.sp b/sourcepawn/compiler/tests/fail-callback-returns-array.sp deleted file mode 100644 index fee720f5..00000000 --- a/sourcepawn/compiler/tests/fail-callback-returns-array.sp +++ /dev/null @@ -1,16 +0,0 @@ -String:MyFunction() -{ - new String:egg[10] = "egg"; - return egg; -} - -public crab() -{ - new String:egg[10]; - egg = MyFunction(); -} - -public Function:main() -{ - return MyFunction; -} diff --git a/sourcepawn/compiler/tests/fail-callback-returns-array.txt b/sourcepawn/compiler/tests/fail-callback-returns-array.txt deleted file mode 100644 index da6bec96..00000000 --- a/sourcepawn/compiler/tests/fail-callback-returns-array.txt +++ /dev/null @@ -1 +0,0 @@ -(15) : error 182: functions that return arrays cannot be used as callbacks diff --git a/sourcepawn/compiler/tests/fail-cannot-view-as-void.sp b/sourcepawn/compiler/tests/fail-cannot-view-as-void.sp deleted file mode 100644 index bec4adf4..00000000 --- a/sourcepawn/compiler/tests/fail-cannot-view-as-void.sp +++ /dev/null @@ -1,3 +0,0 @@ -public float egg() { - return view_as(10); -} diff --git a/sourcepawn/compiler/tests/fail-cannot-view-as-void.txt b/sourcepawn/compiler/tests/fail-cannot-view-as-void.txt deleted file mode 100644 index c4631319..00000000 --- a/sourcepawn/compiler/tests/fail-cannot-view-as-void.txt +++ /dev/null @@ -1 +0,0 @@ -(2) : error 144: void cannot be used as a variable type diff --git a/sourcepawn/compiler/tests/fail-coerce-ref-string-to-any.sp b/sourcepawn/compiler/tests/fail-coerce-ref-string-to-any.sp deleted file mode 100644 index fc48d671..00000000 --- a/sourcepawn/compiler/tests/fail-coerce-ref-string-to-any.sp +++ /dev/null @@ -1,9 +0,0 @@ -f(any[] x) -{ -} - -public main() -{ - char x[10]; - f(x[1]); -} diff --git a/sourcepawn/compiler/tests/fail-coerce-ref-string-to-any.txt b/sourcepawn/compiler/tests/fail-coerce-ref-string-to-any.txt deleted file mode 100644 index 4d668d2b..00000000 --- a/sourcepawn/compiler/tests/fail-coerce-ref-string-to-any.txt +++ /dev/null @@ -1 +0,0 @@ -(8) : error 178: cannot coerce char[] to any[]; storage classes differ diff --git a/sourcepawn/compiler/tests/fail-coerce-string-to-any.sp b/sourcepawn/compiler/tests/fail-coerce-string-to-any.sp deleted file mode 100644 index 296f47cb..00000000 --- a/sourcepawn/compiler/tests/fail-coerce-string-to-any.sp +++ /dev/null @@ -1,9 +0,0 @@ -f(any[] x) -{ -} - -public main() -{ - char x[10]; - f(x); -} diff --git a/sourcepawn/compiler/tests/fail-coerce-string-to-any.txt b/sourcepawn/compiler/tests/fail-coerce-string-to-any.txt deleted file mode 100644 index 4d668d2b..00000000 --- a/sourcepawn/compiler/tests/fail-coerce-string-to-any.txt +++ /dev/null @@ -1 +0,0 @@ -(8) : error 178: cannot coerce char[] to any[]; storage classes differ diff --git a/sourcepawn/compiler/tests/fail-ctor-bad-return-type.sp b/sourcepawn/compiler/tests/fail-ctor-bad-return-type.sp deleted file mode 100644 index ee9ad489..00000000 --- a/sourcepawn/compiler/tests/fail-ctor-bad-return-type.sp +++ /dev/null @@ -1,13 +0,0 @@ -native Float:CreateHandle(count); -native CloseHandle(Handle:handle); - -methodmap Handle { - public Handle() = CreateHandle; - public Close() = CloseHandle; -}; - -public main() { - new Handle:handle = Handle(3); - handle.Close(); -} - diff --git a/sourcepawn/compiler/tests/fail-ctor-bad-return-type.txt b/sourcepawn/compiler/tests/fail-ctor-bad-return-type.txt deleted file mode 100644 index 59bc1840..00000000 --- a/sourcepawn/compiler/tests/fail-ctor-bad-return-type.txt +++ /dev/null @@ -1 +0,0 @@ -constructor function must return tag Handle diff --git a/sourcepawn/compiler/tests/fail-default-args-in-public.sp b/sourcepawn/compiler/tests/fail-default-args-in-public.sp deleted file mode 100644 index 97a39802..00000000 --- a/sourcepawn/compiler/tests/fail-default-args-in-public.sp +++ /dev/null @@ -1 +0,0 @@ -public x(param = 1) {} diff --git a/sourcepawn/compiler/tests/fail-default-args-in-public.txt b/sourcepawn/compiler/tests/fail-default-args-in-public.txt deleted file mode 100644 index 01947b24..00000000 --- a/sourcepawn/compiler/tests/fail-default-args-in-public.txt +++ /dev/null @@ -1 +0,0 @@ -(1) : error 059: function argument may not have a default value (variable "param") diff --git a/sourcepawn/compiler/tests/fail-delete-no-dtor.sp b/sourcepawn/compiler/tests/fail-delete-no-dtor.sp deleted file mode 100644 index 73b405b7..00000000 --- a/sourcepawn/compiler/tests/fail-delete-no-dtor.sp +++ /dev/null @@ -1,10 +0,0 @@ -native Handle:CreateHandle(); - -methodmap Handle { - public Handle() = CreateHandle; -}; - -public main() { - new Handle:handle = Handle(); - delete handle; -} diff --git a/sourcepawn/compiler/tests/fail-delete-no-dtor.txt b/sourcepawn/compiler/tests/fail-delete-no-dtor.txt deleted file mode 100644 index f8623d99..00000000 --- a/sourcepawn/compiler/tests/fail-delete-no-dtor.txt +++ /dev/null @@ -1 +0,0 @@ -cannot use delete, methodmap Handle has no destructor diff --git a/sourcepawn/compiler/tests/fail-dtor-extra-args.sp b/sourcepawn/compiler/tests/fail-dtor-extra-args.sp deleted file mode 100644 index d6bf6d5b..00000000 --- a/sourcepawn/compiler/tests/fail-dtor-extra-args.sp +++ /dev/null @@ -1,8 +0,0 @@ -native Q(X:handle, a); - -methodmap X { - public ~X() = Q; -} - -public main() { -} diff --git a/sourcepawn/compiler/tests/fail-dtor-extra-args.txt b/sourcepawn/compiler/tests/fail-dtor-extra-args.txt deleted file mode 100644 index 2f86263c..00000000 --- a/sourcepawn/compiler/tests/fail-dtor-extra-args.txt +++ /dev/null @@ -1 +0,0 @@ -destructors cannot have extra arguments diff --git a/sourcepawn/compiler/tests/fail-dtor-non-native.sp b/sourcepawn/compiler/tests/fail-dtor-non-native.sp deleted file mode 100644 index 6addca89..00000000 --- a/sourcepawn/compiler/tests/fail-dtor-non-native.sp +++ /dev/null @@ -1,10 +0,0 @@ -Q(X:handle) -{ -} - -methodmap X { - public ~X() = Q; -} - -public main() { -} diff --git a/sourcepawn/compiler/tests/fail-dtor-non-native.txt b/sourcepawn/compiler/tests/fail-dtor-non-native.txt deleted file mode 100644 index 43b690c2..00000000 --- a/sourcepawn/compiler/tests/fail-dtor-non-native.txt +++ /dev/null @@ -1 +0,0 @@ -destructors must be native functions diff --git a/sourcepawn/compiler/tests/fail-dtor-returns-value.sp b/sourcepawn/compiler/tests/fail-dtor-returns-value.sp deleted file mode 100644 index 26632f9c..00000000 --- a/sourcepawn/compiler/tests/fail-dtor-returns-value.sp +++ /dev/null @@ -1,8 +0,0 @@ -native bool:Q(); - -methodmap X { - public ~X() = Q; -} - -public main() { -} diff --git a/sourcepawn/compiler/tests/fail-dtor-returns-value.txt b/sourcepawn/compiler/tests/fail-dtor-returns-value.txt deleted file mode 100644 index 3825f3f5..00000000 --- a/sourcepawn/compiler/tests/fail-dtor-returns-value.txt +++ /dev/null @@ -1 +0,0 @@ -destructor should not have an explicit return type diff --git a/sourcepawn/compiler/tests/fail-duplicate-getter.sp b/sourcepawn/compiler/tests/fail-duplicate-getter.sp deleted file mode 100644 index 0cdfd6a0..00000000 --- a/sourcepawn/compiler/tests/fail-duplicate-getter.sp +++ /dev/null @@ -1,9 +0,0 @@ -methodmap Crab { - property int Crab { - public native get(); - public native get(); - } -} - -public main() { -} diff --git a/sourcepawn/compiler/tests/fail-duplicate-getter.txt b/sourcepawn/compiler/tests/fail-duplicate-getter.txt deleted file mode 100644 index c2b4feee..00000000 --- a/sourcepawn/compiler/tests/fail-duplicate-getter.txt +++ /dev/null @@ -1 +0,0 @@ -getter for Crab already exists diff --git a/sourcepawn/compiler/tests/fail-duplicate-methods.sp b/sourcepawn/compiler/tests/fail-duplicate-methods.sp deleted file mode 100644 index 071d9d7a..00000000 --- a/sourcepawn/compiler/tests/fail-duplicate-methods.sp +++ /dev/null @@ -1,8 +0,0 @@ -native X:Crab(X:x); -methodmap X { - public X2() = Crab; - public X2() = Crab; -} - -public main() { -} diff --git a/sourcepawn/compiler/tests/fail-duplicate-methods.txt b/sourcepawn/compiler/tests/fail-duplicate-methods.txt deleted file mode 100644 index f56c4be2..00000000 --- a/sourcepawn/compiler/tests/fail-duplicate-methods.txt +++ /dev/null @@ -1 +0,0 @@ -X2 was already defined on this methodmap diff --git a/sourcepawn/compiler/tests/fail-duplicate-property.sp b/sourcepawn/compiler/tests/fail-duplicate-property.sp deleted file mode 100644 index 25a42aaa..00000000 --- a/sourcepawn/compiler/tests/fail-duplicate-property.sp +++ /dev/null @@ -1,7 +0,0 @@ -methodmap Crab { - property int Crab; - property int Crab; -} - -public main() { -} diff --git a/sourcepawn/compiler/tests/fail-duplicate-property.txt b/sourcepawn/compiler/tests/fail-duplicate-property.txt deleted file mode 100644 index 8e4bf6a9..00000000 --- a/sourcepawn/compiler/tests/fail-duplicate-property.txt +++ /dev/null @@ -1 +0,0 @@ -Crab was already defined on this methodmap diff --git a/sourcepawn/compiler/tests/fail-dynamic-array-bad-type.sp b/sourcepawn/compiler/tests/fail-dynamic-array-bad-type.sp deleted file mode 100644 index 14a53f54..00000000 --- a/sourcepawn/compiler/tests/fail-dynamic-array-bad-type.sp +++ /dev/null @@ -1,4 +0,0 @@ -public main() -{ - int[] x = new float[3]; -} diff --git a/sourcepawn/compiler/tests/fail-dynamic-array-bad-type.txt b/sourcepawn/compiler/tests/fail-dynamic-array-bad-type.txt deleted file mode 100644 index d2e8545a..00000000 --- a/sourcepawn/compiler/tests/fail-dynamic-array-bad-type.txt +++ /dev/null @@ -1 +0,0 @@ -(3) : error 164: allocated array type 'float' doesn't match original type 'int' diff --git a/sourcepawn/compiler/tests/fail-indeterminate-string-literal.sp b/sourcepawn/compiler/tests/fail-indeterminate-string-literal.sp deleted file mode 100644 index 27bb31ea..00000000 --- a/sourcepawn/compiler/tests/fail-indeterminate-string-literal.sp +++ /dev/null @@ -1,8 +0,0 @@ -native print(const char[] str); -native printnum(num); - -public main() -{ - char[] egg = "!\n"; - return sizeof(egg); -} diff --git a/sourcepawn/compiler/tests/fail-indeterminate-string-literal.txt b/sourcepawn/compiler/tests/fail-indeterminate-string-literal.txt deleted file mode 100644 index ac9a565b..00000000 --- a/sourcepawn/compiler/tests/fail-indeterminate-string-literal.txt +++ /dev/null @@ -1 +0,0 @@ -(7) : error 163: indeterminate array size in "sizeof" expression (symbol "egg") diff --git a/sourcepawn/compiler/tests/fail-method-name-too-long.sp b/sourcepawn/compiler/tests/fail-method-name-too-long.sp deleted file mode 100644 index 55e07fac..00000000 --- a/sourcepawn/compiler/tests/fail-method-name-too-long.sp +++ /dev/null @@ -1,7 +0,0 @@ -methodmap ThisNameIsReallyLongWowItsVeryLong { - public ThisNameIsReallyLongWowItsVeryLong() { - } -} - -public main() { -} diff --git a/sourcepawn/compiler/tests/fail-method-name-too-long.txt b/sourcepawn/compiler/tests/fail-method-name-too-long.txt deleted file mode 100644 index b6856a3e..00000000 --- a/sourcepawn/compiler/tests/fail-method-name-too-long.txt +++ /dev/null @@ -1 +0,0 @@ -fully-qualified name "ThisNameIsReallyLongWowItsVeryLong.ThisNameIsReallyLongWowItsVeryLong" is too long, would be truncated to "ThisNameIsReallyLongWowItsVeryLong.ThisNameIsReallyLongWowItsVe" diff --git a/sourcepawn/compiler/tests/fail-method-on-array.sp b/sourcepawn/compiler/tests/fail-method-on-array.sp deleted file mode 100644 index 212d1879..00000000 --- a/sourcepawn/compiler/tests/fail-method-on-array.sp +++ /dev/null @@ -1,12 +0,0 @@ -native CloseHandle(Handle:handle); - -methodmap Handle { - public Close() = CloseHandle; -}; - -public main() -{ - new Handle:x[2]; - - x.Close(); -} diff --git a/sourcepawn/compiler/tests/fail-method-on-array.txt b/sourcepawn/compiler/tests/fail-method-on-array.txt deleted file mode 100644 index e01ded18..00000000 --- a/sourcepawn/compiler/tests/fail-method-on-array.txt +++ /dev/null @@ -1 +0,0 @@ -cannot call methods on an array diff --git a/sourcepawn/compiler/tests/fail-method-on-function.sp b/sourcepawn/compiler/tests/fail-method-on-function.sp deleted file mode 100644 index 4dd50a98..00000000 --- a/sourcepawn/compiler/tests/fail-method-on-function.sp +++ /dev/null @@ -1,10 +0,0 @@ -native CloseHandle(Handle:handle); - -methodmap Handle { - public Close() = CloseHandle; -}; - -public main() -{ - main.Close(); -} diff --git a/sourcepawn/compiler/tests/fail-method-on-function.txt b/sourcepawn/compiler/tests/fail-method-on-function.txt deleted file mode 100644 index 47a85b6f..00000000 --- a/sourcepawn/compiler/tests/fail-method-on-function.txt +++ /dev/null @@ -1 +0,0 @@ -cannot call methods on a function diff --git a/sourcepawn/compiler/tests/fail-method-requires-brace.sp b/sourcepawn/compiler/tests/fail-method-requires-brace.sp deleted file mode 100644 index c5f05f8e..00000000 --- a/sourcepawn/compiler/tests/fail-method-requires-brace.sp +++ /dev/null @@ -1,8 +0,0 @@ -methodmap Crab { - public Crab() return Crab:5; -}; - -public main() { - new Crab:crab = Crab(); - return _:crab; -} diff --git a/sourcepawn/compiler/tests/fail-method-requires-brace.txt b/sourcepawn/compiler/tests/fail-method-requires-brace.txt deleted file mode 100644 index 986fc3b9..00000000 --- a/sourcepawn/compiler/tests/fail-method-requires-brace.txt +++ /dev/null @@ -1 +0,0 @@ -expected token: "{", but found "return" diff --git a/sourcepawn/compiler/tests/fail-methodmap-as-rvalue.sp b/sourcepawn/compiler/tests/fail-methodmap-as-rvalue.sp deleted file mode 100644 index 1218fca6..00000000 --- a/sourcepawn/compiler/tests/fail-methodmap-as-rvalue.sp +++ /dev/null @@ -1,17 +0,0 @@ -native printnum(x); - -enum X { -}; - -methodmap X { - public X(int y) { - printnum(y); - return view_as(0); - } -}; - -public main() -{ - X x = X(5); - return X; -} diff --git a/sourcepawn/compiler/tests/fail-methodmap-as-rvalue.txt b/sourcepawn/compiler/tests/fail-methodmap-as-rvalue.txt deleted file mode 100644 index 7dfa5277..00000000 --- a/sourcepawn/compiler/tests/fail-methodmap-as-rvalue.txt +++ /dev/null @@ -1 +0,0 @@ -(16) : error 174: symbol 'X' is a type and cannot be used as a value diff --git a/sourcepawn/compiler/tests/fail-methodmap-missing-method.sp b/sourcepawn/compiler/tests/fail-methodmap-missing-method.sp deleted file mode 100644 index 36ebdba5..00000000 --- a/sourcepawn/compiler/tests/fail-methodmap-missing-method.sp +++ /dev/null @@ -1,13 +0,0 @@ -methodmap Duck -{ - public void MyFunc() - { - // this will compile fine until this function is used elsewhere in code - ThisFuncDoesntExist(); - } -}; - -public OnPluginStart() -{ -} - diff --git a/sourcepawn/compiler/tests/fail-methodmap-missing-method.txt b/sourcepawn/compiler/tests/fail-methodmap-missing-method.txt deleted file mode 100644 index e68fb927..00000000 --- a/sourcepawn/compiler/tests/fail-methodmap-missing-method.txt +++ /dev/null @@ -1 +0,0 @@ -(6) : error 017: undefined symbol "ThisFuncDoesntExist" diff --git a/sourcepawn/compiler/tests/fail-mismatch-on-implicit-this.sp b/sourcepawn/compiler/tests/fail-mismatch-on-implicit-this.sp deleted file mode 100644 index 00de8236..00000000 --- a/sourcepawn/compiler/tests/fail-mismatch-on-implicit-this.sp +++ /dev/null @@ -1,9 +0,0 @@ -native CloseHandle(HandleEgg:handle); - -methodmap Handle { - public Close() = CloseHandle; -}; - -public main() -{ -} diff --git a/sourcepawn/compiler/tests/fail-mismatch-on-implicit-this.txt b/sourcepawn/compiler/tests/fail-mismatch-on-implicit-this.txt deleted file mode 100644 index aedab634..00000000 --- a/sourcepawn/compiler/tests/fail-mismatch-on-implicit-this.txt +++ /dev/null @@ -1 +0,0 @@ -method must have a first argument compatible with the methodmap type (Handle) diff --git a/sourcepawn/compiler/tests/fail-missing-arg-comma.sp b/sourcepawn/compiler/tests/fail-missing-arg-comma.sp deleted file mode 100644 index 9e56d2a3..00000000 --- a/sourcepawn/compiler/tests/fail-missing-arg-comma.sp +++ /dev/null @@ -1,4 +0,0 @@ -stock void Function( float array1[ 3 ] float array2[ 3 ] ) -{ - -} diff --git a/sourcepawn/compiler/tests/fail-missing-arg-comma.txt b/sourcepawn/compiler/tests/fail-missing-arg-comma.txt deleted file mode 100644 index 418e8963..00000000 --- a/sourcepawn/compiler/tests/fail-missing-arg-comma.txt +++ /dev/null @@ -1 +0,0 @@ -(1) : error 001: expected token: ")", but found "-identifier-" diff --git a/sourcepawn/compiler/tests/fail-multi-tag-on-implicit-this.sp b/sourcepawn/compiler/tests/fail-multi-tag-on-implicit-this.sp deleted file mode 100644 index f2b6dc74..00000000 --- a/sourcepawn/compiler/tests/fail-multi-tag-on-implicit-this.sp +++ /dev/null @@ -1,9 +0,0 @@ -native CloseHandle({Handle, Egg}:handle); - -methodmap Handle { - public Close() = CloseHandle; -}; - -public main() -{ -} diff --git a/sourcepawn/compiler/tests/fail-multi-tag-on-implicit-this.txt b/sourcepawn/compiler/tests/fail-multi-tag-on-implicit-this.txt deleted file mode 100644 index aedab634..00000000 --- a/sourcepawn/compiler/tests/fail-multi-tag-on-implicit-this.txt +++ /dev/null @@ -1 +0,0 @@ -method must have a first argument compatible with the methodmap type (Handle) diff --git a/sourcepawn/compiler/tests/fail-new-with-no-constructor.sp b/sourcepawn/compiler/tests/fail-new-with-no-constructor.sp deleted file mode 100644 index 51580179..00000000 --- a/sourcepawn/compiler/tests/fail-new-with-no-constructor.sp +++ /dev/null @@ -1,10 +0,0 @@ -methodmap Handle __nullable__ -{ - public native ~Handle(); -}; - -public t() -{ - Handle egg = new Handle(); - delete egg; -} diff --git a/sourcepawn/compiler/tests/fail-new-with-no-constructor.txt b/sourcepawn/compiler/tests/fail-new-with-no-constructor.txt deleted file mode 100644 index d0ac818f..00000000 --- a/sourcepawn/compiler/tests/fail-new-with-no-constructor.txt +++ /dev/null @@ -1 +0,0 @@ -(8) : error 172: methodmap 'Handle' does not have a constructor diff --git a/sourcepawn/compiler/tests/fail-new-with-no-methodmap.sp b/sourcepawn/compiler/tests/fail-new-with-no-methodmap.sp deleted file mode 100644 index 6d666f44..00000000 --- a/sourcepawn/compiler/tests/fail-new-with-no-methodmap.sp +++ /dev/null @@ -1,13 +0,0 @@ -methodmap Handle __nullable__ -{ - public native Handle(); - public native ~Handle(); -}; - -enum Crab {}; - -public t() -{ - Crab egg = new Crab(); - delete egg; -} diff --git a/sourcepawn/compiler/tests/fail-new-with-no-methodmap.txt b/sourcepawn/compiler/tests/fail-new-with-no-methodmap.txt deleted file mode 100644 index 27d51f00..00000000 --- a/sourcepawn/compiler/tests/fail-new-with-no-methodmap.txt +++ /dev/null @@ -1 +0,0 @@ -(11) : error 116: no methodmap or class was found for Crab diff --git a/sourcepawn/compiler/tests/fail-new-with-non-nullable.sp b/sourcepawn/compiler/tests/fail-new-with-non-nullable.sp deleted file mode 100644 index 95684f5d..00000000 --- a/sourcepawn/compiler/tests/fail-new-with-non-nullable.sp +++ /dev/null @@ -1,11 +0,0 @@ -methodmap Handle -{ - public native Handle(); - public native ~Handle(); -}; - -public t() -{ - Handle egg = new Handle(); - delete egg; -} diff --git a/sourcepawn/compiler/tests/fail-new-with-non-nullable.txt b/sourcepawn/compiler/tests/fail-new-with-non-nullable.txt deleted file mode 100644 index 812014e4..00000000 --- a/sourcepawn/compiler/tests/fail-new-with-non-nullable.txt +++ /dev/null @@ -1 +0,0 @@ -(9) : error 171: cannot use 'new' with non-object-like methodmap 'Handle' diff --git a/sourcepawn/compiler/tests/fail-newdecls.sp b/sourcepawn/compiler/tests/fail-newdecls.sp deleted file mode 100644 index 510eef99..00000000 --- a/sourcepawn/compiler/tests/fail-newdecls.sp +++ /dev/null @@ -1,15 +0,0 @@ -native int[] egg6(); -forward float[] egg7(); -new void crab4; - -void bad(int[] yam[] = {1}) -{ -} - -forward void OnPluginStart(); - -public int OnPluginStart() -{ -} - - diff --git a/sourcepawn/compiler/tests/fail-newdecls.txt b/sourcepawn/compiler/tests/fail-newdecls.txt deleted file mode 100644 index 1eb77d2a..00000000 --- a/sourcepawn/compiler/tests/fail-newdecls.txt +++ /dev/null @@ -1,5 +0,0 @@ -(1) : error 141: natives, forwards, and public functions cannot return arrays -(2) : error 141: natives, forwards, and public functions cannot return arrays -(3) : error 143: new-style declarations should not have "new" -(5) : error 121: cannot specify array dimensions on both type and name -(11) : error 180: function return type differs from prototype. expected 'void', but got 'int' diff --git a/sourcepawn/compiler/tests/fail-no-tag-on-implicit-this.sp b/sourcepawn/compiler/tests/fail-no-tag-on-implicit-this.sp deleted file mode 100644 index df7b09f1..00000000 --- a/sourcepawn/compiler/tests/fail-no-tag-on-implicit-this.sp +++ /dev/null @@ -1,9 +0,0 @@ -native CloseHandle(this); - -methodmap Handle { - public Close() = CloseHandle; -}; - -public main() -{ -} diff --git a/sourcepawn/compiler/tests/fail-no-tag-on-implicit-this.txt b/sourcepawn/compiler/tests/fail-no-tag-on-implicit-this.txt deleted file mode 100644 index aedab634..00000000 --- a/sourcepawn/compiler/tests/fail-no-tag-on-implicit-this.txt +++ /dev/null @@ -1 +0,0 @@ -method must have a first argument compatible with the methodmap type (Handle) diff --git a/sourcepawn/compiler/tests/fail-nullable-needs-new.sp b/sourcepawn/compiler/tests/fail-nullable-needs-new.sp deleted file mode 100644 index 6c09a80a..00000000 --- a/sourcepawn/compiler/tests/fail-nullable-needs-new.sp +++ /dev/null @@ -1,11 +0,0 @@ -methodmap Handle __nullable__ -{ - public native Handle(); - public native ~Handle(); -}; - -public t() -{ - Handle egg = Handle(); - delete egg; -} diff --git a/sourcepawn/compiler/tests/fail-nullable-needs-new.txt b/sourcepawn/compiler/tests/fail-nullable-needs-new.txt deleted file mode 100644 index 701fb593..00000000 --- a/sourcepawn/compiler/tests/fail-nullable-needs-new.txt +++ /dev/null @@ -1 +0,0 @@ -(9) : error 170: creating new object 'Handle' requires using 'new' before its constructor diff --git a/sourcepawn/compiler/tests/fail-old-decl-new-types.sp b/sourcepawn/compiler/tests/fail-old-decl-new-types.sp deleted file mode 100644 index deaf3c96..00000000 --- a/sourcepawn/compiler/tests/fail-old-decl-new-types.sp +++ /dev/null @@ -1,8 +0,0 @@ -methodmap X { - public native Float X(); - public native String Z(); - public native T:Z(); -} - -public main() { -} diff --git a/sourcepawn/compiler/tests/fail-old-decl-new-types.txt b/sourcepawn/compiler/tests/fail-old-decl-new-types.txt deleted file mode 100644 index 371fe020..00000000 --- a/sourcepawn/compiler/tests/fail-old-decl-new-types.txt +++ /dev/null @@ -1,3 +0,0 @@ -type "Float" should be "float" in new-style declarations -type "String" should be "char" in new-style declarations -methodmap and class signatures must use new-style type declarations diff --git a/sourcepawn/compiler/tests/fail-property-bad-return-type.sp b/sourcepawn/compiler/tests/fail-property-bad-return-type.sp deleted file mode 100644 index 9bbf7cfe..00000000 --- a/sourcepawn/compiler/tests/fail-property-bad-return-type.sp +++ /dev/null @@ -1,12 +0,0 @@ -native GetCrab(Crab:crab); - -methodmap Crab { - property float Blah { - public get() = GetCrab; - } -} - -public main() { - new Crab:crab = Crab:5; - new x = crab.Blah; -} diff --git a/sourcepawn/compiler/tests/fail-property-bad-return-type.txt b/sourcepawn/compiler/tests/fail-property-bad-return-type.txt deleted file mode 100644 index d9f58f58..00000000 --- a/sourcepawn/compiler/tests/fail-property-bad-return-type.txt +++ /dev/null @@ -1 +0,0 @@ -getter must have the same return type as property Crab (float) diff --git a/sourcepawn/compiler/tests/fail-property-bad-return-value.txt b/sourcepawn/compiler/tests/fail-property-bad-return-value.txt deleted file mode 100644 index 80e10d93..00000000 --- a/sourcepawn/compiler/tests/fail-property-bad-return-value.txt +++ /dev/null @@ -1 +0,0 @@ -(4) : warning 213: tag mismatch diff --git a/sourcepawn/compiler/tests/fail-property-bad-this-type.sp b/sourcepawn/compiler/tests/fail-property-bad-this-type.sp deleted file mode 100644 index 8567e7fc..00000000 --- a/sourcepawn/compiler/tests/fail-property-bad-this-type.sp +++ /dev/null @@ -1,12 +0,0 @@ -native Float:GetCrab(); - -methodmap Crab { - property float Blah { - public get() = GetCrab(); - } -} - -public main() { - new Crab:crab = Crab:5; - new x = crab.Blah; -} diff --git a/sourcepawn/compiler/tests/fail-property-bad-this-type.txt b/sourcepawn/compiler/tests/fail-property-bad-this-type.txt deleted file mode 100644 index e23c2488..00000000 --- a/sourcepawn/compiler/tests/fail-property-bad-this-type.txt +++ /dev/null @@ -1 +0,0 @@ -method must have a first argument compatible with the methodmap type (Crab) diff --git a/sourcepawn/compiler/tests/fail-ref-on-implicit-this.sp b/sourcepawn/compiler/tests/fail-ref-on-implicit-this.sp deleted file mode 100644 index be718f1f..00000000 --- a/sourcepawn/compiler/tests/fail-ref-on-implicit-this.sp +++ /dev/null @@ -1,9 +0,0 @@ -native CloseHandle(&Handle:this); - -methodmap Handle { - public Close() = CloseHandle; -}; - -public main() -{ -} diff --git a/sourcepawn/compiler/tests/fail-ref-on-implicit-this.txt b/sourcepawn/compiler/tests/fail-ref-on-implicit-this.txt deleted file mode 100644 index aedab634..00000000 --- a/sourcepawn/compiler/tests/fail-ref-on-implicit-this.txt +++ /dev/null @@ -1 +0,0 @@ -method must have a first argument compatible with the methodmap type (Handle) diff --git a/sourcepawn/compiler/tests/fail-sizeof-default-arg.sp b/sourcepawn/compiler/tests/fail-sizeof-default-arg.sp deleted file mode 100644 index eb550dcd..00000000 --- a/sourcepawn/compiler/tests/fail-sizeof-default-arg.sp +++ /dev/null @@ -1,9 +0,0 @@ -stock void crab(int[] eggs, int numEggs = sizeof(eggs)) -{ -} - -public main() -{ - int eggs[12]; - crab(eggs); -} diff --git a/sourcepawn/compiler/tests/fail-sizeof-default-arg.txt b/sourcepawn/compiler/tests/fail-sizeof-default-arg.txt deleted file mode 100644 index a5bd9a7c..00000000 --- a/sourcepawn/compiler/tests/fail-sizeof-default-arg.txt +++ /dev/null @@ -1 +0,0 @@ -(1) : error 163: indeterminate array size in "sizeof" expression (symbol "eggs") diff --git a/sourcepawn/compiler/tests/fail-tag-enum-as-implicit-int.sp b/sourcepawn/compiler/tests/fail-tag-enum-as-implicit-int.sp deleted file mode 100644 index 0ac7b42b..00000000 --- a/sourcepawn/compiler/tests/fail-tag-enum-as-implicit-int.sp +++ /dev/null @@ -1,23 +0,0 @@ -native Float:float(x); -native Float:FloatMul(Float:oper1, Float:oper2); - -stock Float:operator*(Float:oper1, oper2) -{ - return FloatMul(oper1, float(oper2)); -} - -native Float:GetRandomFloat(); - -enum _:Rocketeer { - bool:bActivated, - iRockets[20] -}; - -public OnPluginStart() -{ - decl Float:fAngles[3]; - - fAngles[0] = GetRandomFloat() * 360; - fAngles[1] = GetRandomFloat() * 360; - fAngles[2] = GetRandomFloat() * 360; -} diff --git a/sourcepawn/compiler/tests/fail-tag-enum-as-implicit-int.txt b/sourcepawn/compiler/tests/fail-tag-enum-as-implicit-int.txt deleted file mode 100644 index e04c048c..00000000 --- a/sourcepawn/compiler/tests/fail-tag-enum-as-implicit-int.txt +++ /dev/null @@ -1 +0,0 @@ -(11) : error 169: cannot tag an enum as implicit-int diff --git a/sourcepawn/compiler/tests/fail-this-outside-method.sp b/sourcepawn/compiler/tests/fail-this-outside-method.sp deleted file mode 100644 index ec7a9081..00000000 --- a/sourcepawn/compiler/tests/fail-this-outside-method.sp +++ /dev/null @@ -1,3 +0,0 @@ -public OnPluginStart() { - return this; -} diff --git a/sourcepawn/compiler/tests/fail-this-outside-method.txt b/sourcepawn/compiler/tests/fail-this-outside-method.txt deleted file mode 100644 index 34791c58..00000000 --- a/sourcepawn/compiler/tests/fail-this-outside-method.txt +++ /dev/null @@ -1 +0,0 @@ -(2) : error 166: cannot use 'this' outside of a methodmap method or property diff --git a/sourcepawn/compiler/tests/ok-any-in-newdecl.sp b/sourcepawn/compiler/tests/ok-any-in-newdecl.sp deleted file mode 100644 index adf6b802..00000000 --- a/sourcepawn/compiler/tests/ok-any-in-newdecl.sp +++ /dev/null @@ -1,3 +0,0 @@ -public x(any y) -{ -} diff --git a/sourcepawn/compiler/tests/ok-bad-int-cast.sp b/sourcepawn/compiler/tests/ok-bad-int-cast.sp deleted file mode 100644 index d3185535..00000000 --- a/sourcepawn/compiler/tests/ok-bad-int-cast.sp +++ /dev/null @@ -1,4 +0,0 @@ -public main() -{ - new class = int:5; -} diff --git a/sourcepawn/compiler/tests/ok-base-dtor.sp b/sourcepawn/compiler/tests/ok-base-dtor.sp deleted file mode 100644 index aab98556..00000000 --- a/sourcepawn/compiler/tests/ok-base-dtor.sp +++ /dev/null @@ -1,15 +0,0 @@ -native Handle:CreateHandle(count); -native CloseHandle(Handle:handle); - -methodmap Handle { - public Handle() = CreateHandle; - public ~Handle() = CloseHandle; -}; - -methodmap Crab < Handle { -}; - -public main() { - new Crab:crab; - delete crab; -} diff --git a/sourcepawn/compiler/tests/ok-base-type-as-thistag.sp b/sourcepawn/compiler/tests/ok-base-type-as-thistag.sp deleted file mode 100644 index 53b67f53..00000000 --- a/sourcepawn/compiler/tests/ok-base-type-as-thistag.sp +++ /dev/null @@ -1,14 +0,0 @@ -native CloseHandle(Handle:handle); - -methodmap Handle { -}; - -methodmap Crab < Handle { - public Close() = CloseHandle; -}; - -public main() -{ - new Crab:x; - x.Close(); -} diff --git a/sourcepawn/compiler/tests/ok-call-static-method.sp b/sourcepawn/compiler/tests/ok-call-static-method.sp deleted file mode 100644 index 19a887ea..00000000 --- a/sourcepawn/compiler/tests/ok-call-static-method.sp +++ /dev/null @@ -1,12 +0,0 @@ -native printnum(t); - -methodmap X -{ - public static int GetThing() { - return 10; - } -} - -public main() { - printnum(X.GetThing()); -} diff --git a/sourcepawn/compiler/tests/ok-chaining.sp b/sourcepawn/compiler/tests/ok-chaining.sp deleted file mode 100644 index 3a8849d2..00000000 --- a/sourcepawn/compiler/tests/ok-chaining.sp +++ /dev/null @@ -1,38 +0,0 @@ -methodmap Duck -{ - property bool MyProp - { - public get() { - return true; - } - } -}; - -public bool OnPluginStart() -{ - Duck duck = GiveMeADuck(); - - // no compile errors or warnings - if (duck.MyProp) - { - } - - // error 001: expected token: ")", but found "." - // error 029: invalid expression, assumed zero - // error 017: undefined symbol "MyProp" - if (GiveMeADuck().MyProp) - { - } - - // warning 213: tag mismatch - // error 001: expected token: ";", but found "." - // error 029: invalid expression, assumed zero - // error 017: undefined symbol "MyProp" - bool prop = GiveMeADuck().MyProp; - return prop -} - -stock Duck GiveMeADuck() -{ - return Duck:1; -} diff --git a/sourcepawn/compiler/tests/ok-class-arg.sp b/sourcepawn/compiler/tests/ok-class-arg.sp deleted file mode 100644 index 1454638c..00000000 --- a/sourcepawn/compiler/tests/ok-class-arg.sp +++ /dev/null @@ -1,7 +0,0 @@ -f(const char[] class) -{ -} - -public OnPluginStart() -{ -} diff --git a/sourcepawn/compiler/tests/ok-coerce-on-operators.sp b/sourcepawn/compiler/tests/ok-coerce-on-operators.sp deleted file mode 100644 index 643124dd..00000000 --- a/sourcepawn/compiler/tests/ok-coerce-on-operators.sp +++ /dev/null @@ -1,18 +0,0 @@ -enum Handle { - INVALID_HANDLE, -}; - -methodmap Handle {}; -methodmap ArrayList < Handle {}; - -public void MyCommand() -{ - ArrayList myList; - if (INVALID_HANDLE == myList) - { - } - if (myList == INVALID_HANDLE) - { - } -} - diff --git a/sourcepawn/compiler/tests/ok-ctor-dtor.sp b/sourcepawn/compiler/tests/ok-ctor-dtor.sp deleted file mode 100644 index cb5cfbdc..00000000 --- a/sourcepawn/compiler/tests/ok-ctor-dtor.sp +++ /dev/null @@ -1,12 +0,0 @@ -native Handle:CreateHandle(count); -native CloseHandle(Handle:handle); - -methodmap Handle { - public Handle() = CreateHandle; - public ~Handle() = CloseHandle; -}; - -public main() { - new Handle:handle = Handle(3); - delete handle; -} diff --git a/sourcepawn/compiler/tests/ok-dynamic-char.sp b/sourcepawn/compiler/tests/ok-dynamic-char.sp deleted file mode 100644 index 88c7b281..00000000 --- a/sourcepawn/compiler/tests/ok-dynamic-char.sp +++ /dev/null @@ -1,5 +0,0 @@ - -public OnPluginStart() -{ - char[] x = new char[500]; -} diff --git a/sourcepawn/compiler/tests/ok-for-newdecl.sp b/sourcepawn/compiler/tests/ok-for-newdecl.sp deleted file mode 100644 index 575151d2..00000000 --- a/sourcepawn/compiler/tests/ok-for-newdecl.sp +++ /dev/null @@ -1,5 +0,0 @@ -public OnPluginStart() -{ - for (bool x; x;) { - } -} diff --git a/sourcepawn/compiler/tests/ok-inheritance.sp b/sourcepawn/compiler/tests/ok-inheritance.sp deleted file mode 100644 index d7a27aa3..00000000 --- a/sourcepawn/compiler/tests/ok-inheritance.sp +++ /dev/null @@ -1,14 +0,0 @@ -native CloseHandle(Handle:handle); - -methodmap Handle { - public Close() = CloseHandle; -}; - -methodmap Crab < Handle { -}; - -public main() -{ - new Crab:x; - x.Close(); -} diff --git a/sourcepawn/compiler/tests/ok-inline-methods.sp b/sourcepawn/compiler/tests/ok-inline-methods.sp deleted file mode 100644 index 86945bf0..00000000 --- a/sourcepawn/compiler/tests/ok-inline-methods.sp +++ /dev/null @@ -1,13 +0,0 @@ -methodmap Crab { - public Crab(int n) { - return Crab:n; - } - public int Value() { - return _:this; - } -}; - -public main() { - new Crab:crab = Crab(5); - return crab.Value(); -} diff --git a/sourcepawn/compiler/tests/ok-inline-natives.sp b/sourcepawn/compiler/tests/ok-inline-natives.sp deleted file mode 100644 index 733d816b..00000000 --- a/sourcepawn/compiler/tests/ok-inline-natives.sp +++ /dev/null @@ -1,17 +0,0 @@ -methodmap Handle { - public native Handle(); - public native ~Handle(); - public native Handle Clone(); - public native int Size(); - public native float SizeF(); - public native bool Ok(x, y, z); -}; - -public main() { - new Handle:handle = Handle(); - handle.Clone(); - new x = handle.Size(); - new Float:f = handle.SizeF(); - new bool:b = handle.Ok(1, 2, 3); - delete handle; -} diff --git a/sourcepawn/compiler/tests/ok-local-dynamic-bool.sp b/sourcepawn/compiler/tests/ok-local-dynamic-bool.sp deleted file mode 100644 index 454d68b0..00000000 --- a/sourcepawn/compiler/tests/ok-local-dynamic-bool.sp +++ /dev/null @@ -1,5 +0,0 @@ -public int main() -{ - bool[] egg = new bool[10]; -} - diff --git a/sourcepawn/compiler/tests/ok-method-on-const.sp b/sourcepawn/compiler/tests/ok-method-on-const.sp deleted file mode 100644 index ca2092e5..00000000 --- a/sourcepawn/compiler/tests/ok-method-on-const.sp +++ /dev/null @@ -1,14 +0,0 @@ -native CloseHandle(Handle:handle); - -enum Handle { - INVALID_HANDLE = 0, -}; - -methodmap Handle { - public Close() = CloseHandle; -}; - -public main() -{ - INVALID_HANDLE.Close(); -} diff --git a/sourcepawn/compiler/tests/ok-method-on-constref.sp b/sourcepawn/compiler/tests/ok-method-on-constref.sp deleted file mode 100644 index 6a147215..00000000 --- a/sourcepawn/compiler/tests/ok-method-on-constref.sp +++ /dev/null @@ -1,16 +0,0 @@ -native CloseHandle(Handle:handle); - -methodmap Handle { - public Close() = CloseHandle; -}; - -f(const &Handle:x) -{ - x.Close() -} - -public main() -{ - new Handle:x; - f(x) -} diff --git a/sourcepawn/compiler/tests/ok-method-on-element.sp b/sourcepawn/compiler/tests/ok-method-on-element.sp deleted file mode 100644 index 1feca10e..00000000 --- a/sourcepawn/compiler/tests/ok-method-on-element.sp +++ /dev/null @@ -1,11 +0,0 @@ -native CloseHandle(Handle:handle); - -methodmap Handle { - public Close() = CloseHandle; -}; - -public main() -{ - new Handle:x[2]; - x[1].Close(); -} diff --git a/sourcepawn/compiler/tests/ok-method-on-ref.sp b/sourcepawn/compiler/tests/ok-method-on-ref.sp deleted file mode 100644 index b28af861..00000000 --- a/sourcepawn/compiler/tests/ok-method-on-ref.sp +++ /dev/null @@ -1,16 +0,0 @@ -native CloseHandle(Handle:handle); - -methodmap Handle { - public Close() = CloseHandle; -}; - -f(&Handle:x) -{ - x.Close() -} - -public main() -{ - new Handle:x; - f(x) -} diff --git a/sourcepawn/compiler/tests/ok-method-on-scalar.sp b/sourcepawn/compiler/tests/ok-method-on-scalar.sp deleted file mode 100644 index 007b5a98..00000000 --- a/sourcepawn/compiler/tests/ok-method-on-scalar.sp +++ /dev/null @@ -1,13 +0,0 @@ -native CloneHandle(Handle:handle); -native CloseHandle(Handle:handle); - -methodmap Handle { - public Clone() = CloneHandle; - public Close() = CloseHandle; -}; - -public main() -{ - new Handle:x; - x.Close(); -} diff --git a/sourcepawn/compiler/tests/ok-methodmap-semis.sp b/sourcepawn/compiler/tests/ok-methodmap-semis.sp deleted file mode 100644 index dfff64c8..00000000 --- a/sourcepawn/compiler/tests/ok-methodmap-semis.sp +++ /dev/null @@ -1,20 +0,0 @@ -#pragma semicolon 1 - -native IsValidEntity(entity); - -methodmap Entity -{ - public Entity(const char[] className) { - return Entity:CreateEntityByName(className); - } - - property bool IsValid { - public get() { - return IsValidEntity(_:this); - } - } -}; - -public main() -{ -} diff --git a/sourcepawn/compiler/tests/ok-new-decl-args.sp b/sourcepawn/compiler/tests/ok-new-decl-args.sp deleted file mode 100644 index c2e25745..00000000 --- a/sourcepawn/compiler/tests/ok-new-decl-args.sp +++ /dev/null @@ -1,44 +0,0 @@ -stock A(int n) -{ -} - -stock B(int n[10]) -{ -} - -stock C(int[] n) -{ -} - -enum E1: { -} -enum E2 { -} - -stock D(E1 t) -{ -} - -stock E(E2 t) -{ -} - -stock F(const int n[10]) { -} - -stock G(int& n) -{ -} - -public main() -{ - new x[10] - new t - A(1) - B(x) - C(x) - D(E1:5) - E(E2:5) - F(x) - G(t) -} diff --git a/sourcepawn/compiler/tests/ok-new-dynamic-array-syntax.sp b/sourcepawn/compiler/tests/ok-new-dynamic-array-syntax.sp deleted file mode 100644 index ef3f8ac4..00000000 --- a/sourcepawn/compiler/tests/ok-new-dynamic-array-syntax.sp +++ /dev/null @@ -1,10 +0,0 @@ -native printnum(num); - -public main() -{ - new x = 4; - new y = 8; - int[][] v = new int[4][8]; - v[2][3] = 9; - printnum(v[2][3]); -} diff --git a/sourcepawn/compiler/tests/ok-new-with-nullable-methodmap.sp b/sourcepawn/compiler/tests/ok-new-with-nullable-methodmap.sp deleted file mode 100644 index 700d5c9f..00000000 --- a/sourcepawn/compiler/tests/ok-new-with-nullable-methodmap.sp +++ /dev/null @@ -1,15 +0,0 @@ -native void printnum(int num); - -methodmap Handle __nullable__ -{ - public Handle() { - return Handle:2; - } - public native ~Handle(); -}; - -public main() -{ - Handle egg = new Handle(); - printnum(_:egg); -} diff --git a/sourcepawn/compiler/tests/ok-newdecl-const.sp b/sourcepawn/compiler/tests/ok-newdecl-const.sp deleted file mode 100644 index 4a013a49..00000000 --- a/sourcepawn/compiler/tests/ok-newdecl-const.sp +++ /dev/null @@ -1,12 +0,0 @@ -// both fine -const MY_CONST = 1; -const Float:FLOAT_CONST = 1.0; - -// error 020: invalid symbol name "" -const int MY_INT_COST = 1; -// error 001: expected token: "=", but found "-identifier-" -const float MY_FLOAT_CONST = 1.0; - -public main() -{ -} diff --git a/sourcepawn/compiler/tests/ok-newdecls.sp b/sourcepawn/compiler/tests/ok-newdecls.sp deleted file mode 100644 index 581e0131..00000000 --- a/sourcepawn/compiler/tests/ok-newdecls.sp +++ /dev/null @@ -1,50 +0,0 @@ -native egg(); -native void egg2(); -native int egg3(); -native bool egg4(); -native bool:egg5(); - -new crab; -new crab2 = 5; -bool crab3 = true; -int crab4 = 6; -new crab5[] = {1, 2, 3}; -bool crab7[] = {false, true, true} -char crab8[] = "hello" - -native float operator*(float oper1, float oper2) = FloatMul; - -forward void OnPluginStart(); - -public int Crab() -{ -} - -public float Crab2() -{ -} - -public Crab3() -{ -} - -stock char[] Crab4() -{ - new String:t[5] = "egg"; - return t; -} - -new yam, yam2, yam3 -new Float:ham, bool:ham2; -int cram, cram2, cram3; -new cram4[] = {1, 2}, cram5[] = {3, 4, 7} -int cram6[] = {1, 2}, cram7[] = {3, 4, 7} - -public OnPluginStart() -{ - new String:t[5]; - t = Crab4(); - cram4[0] = 2 - cram5[2] = 2 - cram7[2] = 2 -} diff --git a/sourcepawn/compiler/tests/ok-null-compare.sp b/sourcepawn/compiler/tests/ok-null-compare.sp deleted file mode 100644 index 044c0bfd..00000000 --- a/sourcepawn/compiler/tests/ok-null-compare.sp +++ /dev/null @@ -1,19 +0,0 @@ -enum Handle: -{ -} - -methodmap Handle __nullable__ -{ -} - -methodmap StringMap < Handle -{ -} - -native Log(const char[] fmt, any:...) - -public main() -{ - StringMap f - Log("hello %d", f != null) -} diff --git a/sourcepawn/compiler/tests/ok-properties.sp b/sourcepawn/compiler/tests/ok-properties.sp deleted file mode 100644 index 52b26b51..00000000 --- a/sourcepawn/compiler/tests/ok-properties.sp +++ /dev/null @@ -1,29 +0,0 @@ -native Float:GetCrabWhat(Crab:crab); - -methodmap Crab { - public Crab(int n) { - return Crab:n; - } - property Crab Yams { - public get() { - return Crab:5; - } - } - property int Blah { - public native get(); - } - property float What { - public get() = GetCrabWhat; - } -} - -print(n) { - return n -} - -public main() { - new Crab:crab = Crab(10); - print(_:crab.Yams.Yams.Yams) - print(crab.Blah); - print(_:crab.What); -} diff --git a/sourcepawn/compiler/tests/ok-reparse-delete.sp b/sourcepawn/compiler/tests/ok-reparse-delete.sp deleted file mode 100644 index 6886cdea..00000000 --- a/sourcepawn/compiler/tests/ok-reparse-delete.sp +++ /dev/null @@ -1,12 +0,0 @@ -methodmap Handle { - public native ~Handle(); -} - -stock Crab(Handle h) -{ - delete h; -} - -public main() -{ -} diff --git a/sourcepawn/compiler/tests/ok-setter-no-getter.sp b/sourcepawn/compiler/tests/ok-setter-no-getter.sp deleted file mode 100644 index 86c28fd6..00000000 --- a/sourcepawn/compiler/tests/ok-setter-no-getter.sp +++ /dev/null @@ -1,12 +0,0 @@ -methodmap Crab -{ - property int X { - public native set(int value); - } -} - -public main() -{ - Crab crab; - crab.X = 12; -} diff --git a/sourcepawn/compiler/tests/ok-static-stock.sp b/sourcepawn/compiler/tests/ok-static-stock.sp deleted file mode 100644 index 73516697..00000000 --- a/sourcepawn/compiler/tests/ok-static-stock.sp +++ /dev/null @@ -1,13 +0,0 @@ -static stock Blah() -{ -} - -static stock void Blah2() -{ -} - -public main() -{ - Blah(); - Blah2(); -} diff --git a/sourcepawn/compiler/tests/ok-static-stocks-1.sp b/sourcepawn/compiler/tests/ok-static-stocks-1.sp deleted file mode 100644 index bf523238..00000000 --- a/sourcepawn/compiler/tests/ok-static-stocks-1.sp +++ /dev/null @@ -1,5 +0,0 @@ -static stock const X = 5; -stock static const Y = 6; - -public main() -{} diff --git a/sourcepawn/compiler/tests/ok-static-stocks-2.sp b/sourcepawn/compiler/tests/ok-static-stocks-2.sp deleted file mode 100644 index 2ced8743..00000000 --- a/sourcepawn/compiler/tests/ok-static-stocks-2.sp +++ /dev/null @@ -1,7 +0,0 @@ -static stock const X = 5; -stock static const Y = 6; - -public main() -{ - return X + Y; -} diff --git a/sourcepawn/compiler/tests/ok-trailing-comma-in-literal.sp b/sourcepawn/compiler/tests/ok-trailing-comma-in-literal.sp deleted file mode 100644 index e1876f6d..00000000 --- a/sourcepawn/compiler/tests/ok-trailing-comma-in-literal.sp +++ /dev/null @@ -1,20 +0,0 @@ - -new String:oldArray[][] = -{ - "string", - "string2", -}; - -char newArray[][] = -{ - "another string", - "more strings", -}; - -native Print( const String:string[] ); - -public OnPluginStart() -{ - Print( oldArray[ 0 ] ); - Print( newArray[ 0 ] ); -} diff --git a/sourcepawn/compiler/tests/ok-typed-vararg-in-new-function.sp b/sourcepawn/compiler/tests/ok-typed-vararg-in-new-function.sp deleted file mode 100644 index 3be4a63f..00000000 --- a/sourcepawn/compiler/tests/ok-typed-vararg-in-new-function.sp +++ /dev/null @@ -1,7 +0,0 @@ -methodmap X { - public native void egg(any ...); -}; - -public main() -{ -} diff --git a/sourcepawn/compiler/tests/ok-typedef-func-chars.sp b/sourcepawn/compiler/tests/ok-typedef-func-chars.sp deleted file mode 100644 index 36f8753c..00000000 --- a/sourcepawn/compiler/tests/ok-typedef-func-chars.sp +++ /dev/null @@ -1,26 +0,0 @@ -enum Action: {} -functag public Action:OldFuncTag( String:someString[128] ); -typedef NewFuncTag = function Action ( char someString[128] ); - -native UseOldFuncTag( OldFuncTag func ); -native UseNewFuncTag( NewFuncTag func ); - -public OnPluginStart() -{ - // fine - UseOldFuncTag( MyOldFunc ); - // also fine - UseOldFuncTag( MyNewFunc ); - - // error 100: function prototypes do not match - UseNewFuncTag( MyOldFunc ); - // error 100: function prototypes do not match - UseNewFuncTag( MyNewFunc ); -} - -public Action:MyOldFunc( String:someString[128] ) -{ -} -public Action MyNewFunc( char someString[128] ) -{ -} diff --git a/sourcepawn/compiler/tests/ok-use-aliased-constructor.sp b/sourcepawn/compiler/tests/ok-use-aliased-constructor.sp deleted file mode 100644 index 1dca0339..00000000 --- a/sourcepawn/compiler/tests/ok-use-aliased-constructor.sp +++ /dev/null @@ -1,12 +0,0 @@ -native Handle:CreateHandle(); - -methodmap Handle __nullable__ -{ - public native Handle() = CreateHandle; - public native ~Handle(); -}; - -public main() -{ - CreateHandle(); -} diff --git a/sourcepawn/compiler/tests/ok-varargs.sp b/sourcepawn/compiler/tests/ok-varargs.sp deleted file mode 100644 index 8361c066..00000000 --- a/sourcepawn/compiler/tests/ok-varargs.sp +++ /dev/null @@ -1,7 +0,0 @@ -stock MyFormat( const String:formatString[], ... ) -{ -} - -public main() -{ -} diff --git a/sourcepawn/compiler/tests/ok-view-int-as-float.sp b/sourcepawn/compiler/tests/ok-view-int-as-float.sp deleted file mode 100644 index 74ce7a1d..00000000 --- a/sourcepawn/compiler/tests/ok-view-int-as-float.sp +++ /dev/null @@ -1,3 +0,0 @@ -public float egg() { - return view_as(10); -} diff --git a/sourcepawn/compiler/tests/runtests.py b/sourcepawn/compiler/tests/runtests.py deleted file mode 100644 index ac4c7c30..00000000 --- a/sourcepawn/compiler/tests/runtests.py +++ /dev/null @@ -1,83 +0,0 @@ -# vim: set ts=4 sw=4 tw=99 et: -import os, sys -import argparse -import subprocess - -def run_tests(args): - testdir = os.path.dirname(os.path.abspath(__file__)) - tests = [] - for filename in os.listdir(testdir): - base, ext = os.path.splitext(filename) - if ext == '.sp': - tests += [base] - - failed = False - - for test in tests: - if test.startswith('fail-'): - kind = 'fail' - elif test.startswith('warn-'): - kind = 'warn' - elif test.startswith('ok-'): - kind = 'pass' - - try: - argv = [os.path.abspath(args.spcomp), os.path.join(testdir, test + '.sp')] - p = subprocess.Popen(argv, stdout=subprocess.PIPE, stderr=subprocess.PIPE) - stdout, stderr = p.communicate() - stdout = stdout.decode('utf-8') - stderr = stderr.decode('utf-8') - - smx_path = test + '.smx' - compiled = os.path.exists(smx_path) - if compiled: - os.unlink(smx_path) - - status = 'ok' - if compiled and kind == 'fail': - status = 'fail' - elif not compiled and kind != 'fail': - status = 'fail' - - fails = [] - if status == 'ok' and kind != 'pass': - lines = [] - with open(os.path.join(testdir, test + '.txt')) as fp: - for line in fp: - lines.append(line.strip()) - for line in lines: - if line not in stdout: - fails += [ - 'Expected to find text in stdout: >>>\n', - line, - '<<<\n', - ] - break - - if status == 'fail' or len(fails): - print('Test {0} ... FAIL'.format(test)) - failed = True - sys.stderr.write('FAILED! Dumping stdout/stderr:\n') - sys.stderr.write(stdout) - sys.stderr.write(stderr) - for line in fails: - sys.stderr.write(line) - else: - print('Test {0} ... OK'.format(test)) - - except Exception as exn: - raise - sys.stderr.write('FAILED! {0}\n'.format(exn.message)) - - if failed: - sys.stderr.write('One or more tests failed!\n') - sys.exit(1) - -def main(): - parser = argparse.ArgumentParser() - parser.add_argument('spcomp', type=str, help='Path to spcomp') - args = parser.parse_args() - run_tests(args) - -if __name__ == '__main__': - main() diff --git a/sourcepawn/compiler/tests/warn-bad-upcast.sp b/sourcepawn/compiler/tests/warn-bad-upcast.sp deleted file mode 100644 index a76438db..00000000 --- a/sourcepawn/compiler/tests/warn-bad-upcast.sp +++ /dev/null @@ -1,15 +0,0 @@ -native CloseHandle(Handle:handle); - -methodmap Handle { - public Close() = CloseHandle; -}; - -methodmap Crab { -}; - -public main() -{ - new Crab:x; - new Handle:y; - x = y; -} diff --git a/sourcepawn/compiler/tests/warn-bad-upcast.txt b/sourcepawn/compiler/tests/warn-bad-upcast.txt deleted file mode 100644 index bdb238a4..00000000 --- a/sourcepawn/compiler/tests/warn-bad-upcast.txt +++ /dev/null @@ -1 +0,0 @@ -tag mismatch diff --git a/sourcepawn/compiler/tests/warn-oldstyle-cast.sp b/sourcepawn/compiler/tests/warn-oldstyle-cast.sp deleted file mode 100644 index 5f6c899c..00000000 --- a/sourcepawn/compiler/tests/warn-oldstyle-cast.sp +++ /dev/null @@ -1,18 +0,0 @@ - -#pragma newdecls required - -enum MyType:{}; - -native void Print(MyType value); -native void PrintF(float value); - -public void main() -{ - int val = 2; - MyType otherVal = MyType:val; - - float value2 = Float:val; - - Print(otherVal); - PrintF(value2); -} diff --git a/sourcepawn/compiler/tests/warn-oldstyle-cast.txt b/sourcepawn/compiler/tests/warn-oldstyle-cast.txt deleted file mode 100644 index 21696a51..00000000 --- a/sourcepawn/compiler/tests/warn-oldstyle-cast.txt +++ /dev/null @@ -1,2 +0,0 @@ -(12) : warning 240: 'MyType:' is an old-style tag operation; use view_as(expression) instead -(14) : warning 240: 'Float:' is an old-style tag operation; use view_as(expression) instead diff --git a/sourcepawn/compiler/tokenbuffer.h b/sourcepawn/compiler/tokenbuffer.h deleted file mode 100644 index ce3fa168..00000000 --- a/sourcepawn/compiler/tokenbuffer.h +++ /dev/null @@ -1,35 +0,0 @@ -// vim: set ts=8 sts=2 sw=2 tw=99 et: -#ifndef _sourcepawn_compiler_token_stream_h_ -#define _sourcepawn_compiler_token_stream_h_ - -typedef struct { - int line; - int col; -} token_pos_t; - -typedef struct { - int id; - int value; - char str[sLINEMAX + 1]; - size_t len; - token_pos_t start; - token_pos_t end; -} full_token_t; - -#define MAX_TOKEN_DEPTH 4 - -typedef struct { - // Total number of tokens parsed. - int num_tokens; - - // Number of tokens that we've rewound back to. - int depth; - - // Most recently fetched token. - int cursor; - - // Circular token buffer. - full_token_t tokens[MAX_TOKEN_DEPTH]; -} token_buffer_t; - -#endif // _sourcepawn_compiler_token_stream_h_ diff --git a/sourcepawn/compiler/version.rc b/sourcepawn/compiler/version.rc deleted file mode 100644 index c9f1d7c4..00000000 --- a/sourcepawn/compiler/version.rc +++ /dev/null @@ -1,52 +0,0 @@ -#include -#if defined WIN32 || defined _WIN32 || defined __WIN32__ -# include -#else -# include -#endif -#include - -AppIcon ICON "pawn.ico" - -/* Version information - * - * All strings MUST have an explicit \0. See the Windows SDK documentation - * for details on version information and the VERSIONINFO structure. - */ - -#define VERSIONNAME "smcomp.exe\0" -#define VERSIONDESCRIPTION "SourcePawn Compiler\0" -#define VERSIONPRODUCTNAME "smcomp\0" - -VS_VERSION_INFO VERSIONINFO -FILEVERSION SM_VERSION_FILE -PRODUCTVERSION SM_VERSION_FILE -FILEFLAGSMASK 0x0000003FL -FILEFLAGS 0 -#if defined(WIN32) - FILEOS VOS__WINDOWS32 -#else - FILEOS VOS__WINDOWS16 -#endif -FILETYPE VFT_DLL -BEGIN - BLOCK "StringFileInfo" - BEGIN - BLOCK "040904E4" - BEGIN - VALUE "CompanyName", "(C)1998-2006 ITB CompuPhase, AlliedModders LLC\0" - VALUE "FileDescription", VERSIONDESCRIPTION - VALUE "FileVersion", SM_VERSION_STRING - VALUE "InternalName", VERSIONNAME - VALUE "LegalCopyright", "(C)1998-2006 ITB CompuPhase, AlliedModders LLC\0" - VALUE "OriginalFilename", VERSIONNAME - VALUE "ProductName", VERSIONPRODUCTNAME - VALUE "ProductVersion", SM_VERSION_STRING - END - END - - BLOCK "VarFileInfo" - BEGIN - VALUE "Translation", 0x409, 1252 - END -END diff --git a/sourcepawn/include/smx/smx-headers.h b/sourcepawn/include/smx/smx-headers.h deleted file mode 100644 index 2fb94235..00000000 --- a/sourcepawn/include/smx/smx-headers.h +++ /dev/null @@ -1,177 +0,0 @@ -// vim: set sts=2 ts=8 sw=2 tw=99 et: -// ============================================================================= -// SourcePawn -// Copyright (C) 2004-2008 AlliedModders LLC. All rights reserved. -// ============================================================================= -// -// This program is free software; you can redistribute it and/or modify it under -// the terms of the GNU General Public License, version 3.0, as published by the -// Free Software Foundation. -// -// This program is distributed in the hope that it will be useful, but WITHOUT -// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -// FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -// details. -// -// You should have received a copy of the GNU General Public License along with -// this program. If not, see . -// -// As a special exception, AlliedModders LLC gives you permission to link the -// code of this program (as well as its derivative works) to "Half-Life 2," the -// "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software -// by the Valve Corporation. You must obey the GNU General Public License in -// all respects for all other code used. Additionally, AlliedModders LLC grants -// this exception to all derivative works. AlliedModders LLC defines further -// exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007), -// or . - -#ifndef _INCLUDE_SPFILE_HEADERS_H -#define _INCLUDE_SPFILE_HEADERS_H - -#include -#include - -namespace sp { - -struct SmxConsts -{ - // SourcePawn File Format (SPFF) magic number. - static const uint32_t FILE_MAGIC = 0x53504646; - - // File format verison number. - // 0x0101 - SourcePawn 1.0; initial version used by SourceMod 1.0. - // 0x0102 - SourcePawn 1.1; used by SourceMod 1.1+. - // 0x0200 - Used by spcomp2. - // - // The major version bits (8-15) indicate a product number. Consumers should - // reject any version for a different product. - // - // The minor version bits (0-7) indicate a compatibility revision. Any minor - // version higher than the current version should be rejected. - static const uint16_t SP1_VERSION_1_0 = 0x0101; - static const uint16_t SP1_VERSION_1_1 = 0x0102; - static const uint16_t SP1_VERSION_1_7 = 0x0107; - static const uint16_t SP1_VERSION_MIN = SP1_VERSION_1_0; - static const uint16_t SP1_VERSION_MAX = SP1_VERSION_1_7; - static const uint16_t SP2_VERSION_MIN = 0x0200; - static const uint16_t SP2_VERSION_MAX = 0x0200; - - // Compression types. - static const uint8_t FILE_COMPRESSION_NONE = 0; - static const uint8_t FILE_COMPRESSION_GZ = 1; - - // SourcePawn 1. - static const uint8_t CODE_VERSION_JIT_1_0 = 9; - static const uint8_t CODE_VERSION_JIT_1_1 = 10; - static const uint8_t CODE_VERSION_JIT_1_7 = 11; - static const uint8_t CODE_VERSION_SP1_MIN = CODE_VERSION_JIT_1_0; - static const uint8_t CODE_VERSION_SP1_MAX = CODE_VERSION_JIT_1_1; - - // For SP1 consumers, the container version may not be checked, but usually - // the code version is. This constant allows newer containers to be rejected - // in those applications. - static const uint8_t CODE_VERSION_REJECT = 0x7F; -}; - -// These structures are byte-packed. -#if defined __GNUC__ -# pragma pack(1) -#else -# pragma pack(push) -# pragma pack(1) -#endif - -// The very first bytes in a .smx file. The .smx file format is a container for -// arbitrary sections, though to actually load a .smx file certain sections -// must be present. The on-disk format has four major regions, in order: -// 1. The header (sp_file_hdr_t). -// 2. The section list (sp_file_section_t). -// 3. The string table. -// 4. The section contents. -// -// Although any part of the file after the header can be compressed, by default -// only the section contents are, and the section list and string table are not. -typedef struct sp_file_hdr_s -{ - // Magic number and version number. - uint32_t magic; - uint16_t version; - - // disksize, imagesize, and dataoffs (at the end) describe a region of the - // file that may be compressed. The region must occur after the initial - // sp_file_hdr_t header. For SourceMod compatibility, the meanings are as - // follows. - // - // Without compression: - // imagesize is the amount of bytes that must be read into memory to parse - // the SMX container, starting from the first byte of the file. - // disksize is undefined. - // dataoffs is undefined. - // - // With compression: - // dataoffs is an offset to the start of the compression region. - // disksize is the length of the compressed region, in bytes, plus dataoffs. - // imagesize is the size of the entire SMX container after decompression. - // - // This means that at least |imagesize-dataoffs| must be allocated to - // decompress, and the compressed region's length is |datasize-dataoffs|. - // - // The compressed region should always be expanded "in-place". That is, to - // parse the container, the compressed bytes should be replaced with - // decompressed bytes. - // - // Note: This scheme may seem odd. It's a combination of historical debt and - // previously unspecified behavior. The original .amx file format contained - // an on-disk structure that supported an endian-agnostic variable-length - // encoding of its data section, and this structure was loaded directly into - // memory and used as the VM context. AMX Mod X later developed a container - // format called ".amxx" as a "universal binary" for 32-bit and 64-bit - // plugins. This format dropped compact encoding, but supported gzip. The - // disksize/imagesize oddness made its way to this file format. When .smx - // was created for SourceMod, it persisted even though AMX was dropped - // entirely. So it goes. - uint8_t compression; - uint32_t disksize; - uint32_t imagesize; - - // Number of named file sections. - uint8_t sections; - - // Offset to the string table. Each string is null-terminated. The string - // table is only used for strings related to parsing the container itself. - // For SourcePawn, a separate ".names" section exists for Pawn-specific data. - uint32_t stringtab; - - // Offset to where compression begins. - uint32_t dataoffs; -} sp_file_hdr_t; - -// Each section is written immediately after the header. -typedef struct sp_file_section_s -{ - uint32_t nameoffs; /**< Offset into the string table. */ - uint32_t dataoffs; /**< Offset into the file for the section contents. */ - uint32_t size; /**< Size of this section's contents. */ -} sp_file_section_t; - -// Code section. This is used only in SP1, but is emitted by default for legacy -// systems which check |codeversion| but not the SMX file version. -typedef struct sp_file_code_s -{ - uint32_t codesize; /**< Size of the code section. */ - uint8_t cellsize; /**< Cellsize in bytes. */ - uint8_t codeversion; /**< Version of opcodes supported. */ - uint16_t flags; /**< Flags. */ - uint32_t main; /**< Address to "main". */ - uint32_t code; /**< Offset to bytecode, relative to the start of this section. */ -} sp_file_code_t; - -#if defined __GNUC__ -# pragma pack() -#else -# pragma pack(pop) -#endif - -} // namespace sp - -#endif //_INCLUDE_SPFILE_HEADERS_H diff --git a/sourcepawn/include/smx/smx-rtti.h b/sourcepawn/include/smx/smx-rtti.h deleted file mode 100644 index 9b8dec22..00000000 --- a/sourcepawn/include/smx/smx-rtti.h +++ /dev/null @@ -1,218 +0,0 @@ -// vim: set sts=2 ts=8 sw=2 tw=99 et: -// ============================================================================= -// SourcePawn -// Copyright (C) 2004-2014 AlliedModders LLC. All rights RESERVED. -// ============================================================================= -// -// This program is free software; you can redistribute it and/or modify it under -// the terms of the GNU General Public License, version 3.0, as published by the -// Free Software Foundation. -// -// This program is distributed in the hope that it will be useful, but WITHOUT -// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -// FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -// details. -// -// You should have received a copy of the GNU General Public License along with -// this program. If not, see . -// -// As a special exception, AlliedModders LLC gives you permission to link the -// code of this program (as well as its derivative works) to "Half-Life 2," the -// "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software -// by the Valve Corporation. You must obey the GNU General Public License in -// all respects for all other code used. Additionally, AlliedModders LLC grants -// this exception to all derivative works. AlliedModders LLC defines further -// exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007), -// or . - -#ifndef _INCLUDE_SPFILE_HEADERS_v2_H -#define _INCLUDE_SPFILE_HEADERS_v2_H - -#include - -namespace sp { - -// These structures are byte-packed. -#if defined __GNUC__ -# pragma pack(1) -#else -# pragma pack(push) -# pragma pack(1) -#endif - -// Tables present in smx v2: -// .names Blob of null-terminated strings. -// .methods Table of smx_method_t entries. -// .pcode Blob of smx_pcode_header_t entries. -// .globals Table of smx_global_var_t entries. -// .types Blob of type information. - -// TypeSpec is a variable-length encoding referenced anywhere that "typespec" -// is specified. -// -// Whenever a TypeSpec is referenced from outside the .types table, specifically -// as a "typeid", it has an encoding to save space: If the id is < 0x20, then -// the id is a single-byte TypeSpec. Otherwise, the |id - 0x20| is an offset -// into the .types section. -enum class TypeSpec : uint8_t -{ - // The void type is special in that it is not a storable type. - void_t = 0x0, - - // Standard C++ datatypes. - boolean = 0x1, - RESERVED_int8 = 0x2, - RESERVED_uint8 = 0x3, - RESERVED_int16 = 0x4, - RESERVED_uint16 = 0x5, - int32 = 0x6, - RESERVED_uint32 = 0x7, - RESERVED_int64 = 0x8, - RESERVED_uint64 = 0x9, - - // platform-width int and uint. - RESERVED_intptr = 0xA, - RESERVED_uintptr = 0xB, - - float32 = 0xC, - RESERVED_float64 = 0xD, - - // char8 is semantically an alias for int8. - char8 = 0xE, - - RESERVED_char32 = 0xF, // Full unicode point. - - RESERVED_string = 0x16, // String reference. - RESERVED_object = 0x17, // Opaque object reference. - - // Followed by an int32 index into the .classes table. - RESERVED_classdef = 0x40, - - // Followed by an int32 index into the .structs table. - RESERVED_structdef = 0x41, - - // Followed by: - // [int8 formalCount] ; Number of formal parameters, counting varargs. - // [typespec *formals] ; Sequence of formal parameter specifications. - // - // When the type spec is for a method definition (for example, the .method - // table), then each type in |formals| must begin with "named" (0x7e) or, - // if it is the last formal, may be "variadic" (0x7a). - method = 0x50, - - // Fixed arrays have their size as part of their type, are copied by-value, - // and passed by-reference. - // - // Followed by: - // typespec type ; Type specification of innermost elements. - // uint8 rank ; Number of dimensions - // int32* dims ; One dimension for each rank. - fixedarray = 0x60, - - // Arrays are true arrays. They are copied by-reference and passed by- - // reference. - // - // Followed by: - // typesec type ; Type specification of innermost elements. - // uint8 rank ; Number of dimensions. - RESERVED_array = 0x61, - - // Only legal as the initial byte or byte following "named" (0x7e) in a - // parameter for a method signature. - // - // Followed by a typespec. Only typespecs < 0x60 ar elegal. - byref = 0x70, - - // Only legal as the initial byte or byte following "named" (0x7e) in a - // parameter for a method signature. - // - // Followed by a typespec. - variadic = 0x7A, - - // Only legal as the initial byte in a parameter or local variable signature. - // - // Followed by: - // uint32 name ; Index into the .names section. - // typespec type ; Type. - named = 0x7E, - - // For readability, this may be emitted at the end of typespec lists. It must - // not be emitted at the end of nested typespecs. - terminator = 0x7F -}; - -// Flags for method definitions. -enum class MethodFlags : uint32_t -{ - STATIC = 0x1, - VARIADIC = 0x2, - PUBLIC = 0x4, - NATIVE = 0x8, - OPTIONAL = 0x10 -}; - -// Specifies an entry in the .methods table. -struct smx_method_t -{ - // Offset into the .names section. - uint32_t name; - - MethodFlags flags; - - // Offset into .types, which must point at a TypeSpec::method. - uint32_t typespec; - - // Offset into .pcode. If flags contains NATIVE, this must be 0. - uint32_t address; -}; - -enum class GlobalVarFlags : uint32_t -{ - PUBLIC = 0x04, - CONST = 0x08 -}; - -// Specifies an entry in the .globals table. -struct smx_global_var_t -{ - // Offset into the .names section. - uint32_t name; - - GlobalVarFlags flags; - - // TypeId of the global. - uint32_t type_id; -}; - -// Specifies the layout we expect at a valid pcode starting position. -struct smx_pcode_header_t -{ - // Must be 0. - uint32_t reserved; - - // Number of local variables. - uint16_t nlocals; - - // Maximum depth of the operand stack. - uint16_t max_depth; - - // Pointer to .types section where local information begins. - uint32_t local_specs; - - // Number of bytes of pcode in the method. - uint32_t length; -}; - -// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! -// DO NOT DEFINE NEW STRUCTURES BELOW. -// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! - -#if defined __GNUC__ -# pragma pack() -#else -# pragma pack(pop) -#endif - -} // namespace sp - -#endif // _INCLUDE_SPFILE_HEADERS_v2_H diff --git a/sourcepawn/include/smx/smx-v1-opcodes.h b/sourcepawn/include/smx/smx-v1-opcodes.h deleted file mode 100644 index 51d42329..00000000 --- a/sourcepawn/include/smx/smx-v1-opcodes.h +++ /dev/null @@ -1,269 +0,0 @@ -// vim: set sts=2 ts=8 sw=2 tw=99 et: -// ============================================================================= -// SourcePawn -// Copyright (C) 2004-2014 AlliedModders LLC. All rights reserved. -// ============================================================================= -// -// This program is free software; you can redistribute it and/or modify it under -// the terms of the GNU General Public License, version 3.0, as published by the -// Free Software Foundation. -// -// This program is distributed in the hope that it will be useful, but WITHOUT -// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -// FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -// details. -// -// You should have received a copy of the GNU General Public License along with -// this program. If not, see . -// -// As a special exception, AlliedModders LLC gives you permission to link the -// code of this program (as well as its derivative works) to "Half-Life 2," the -// "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software -// by the Valve Corporation. You must obey the GNU General Public License in -// all respects for all other code used. Additionally, AlliedModders LLC grants -// this exception to all derivative works. AlliedModders LLC defines further -// exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007), -// or . - -#ifndef _INCLUDE_SPFILE_HEADERS_v1_opcodes_H -#define _INCLUDE_SPFILE_HEADERS_v1_opcodes_H - -#include -#include - -namespace sp { - -// Opcodes labelled "UNGEN" cannot be generated by the compiler. Quite a few, -// if they could, make little sense in the context of a JIT and could not -// work anyway. Opcodes technically present in sc4.c/sc7.c (respectively, -// the code emitter and peephole optimizer) are not necessarily ever generated. -// For example, lref.pri and lref.alt would be used if a reference could be -// stored in the global scope; but they can't, so they are unreachable. -// -// Most opcodes have been manually verified. A few have not, as they are only -// produced by the peephole optimizer, or not produced at all, or eliminated -// during optimization. We generate them anyway, just in case, but they have -// not been tested. -// lref.s.alt (phopt only) -// stor.alt (never) -// stor.s.alt (never) -// sref.s.alt (never) -// lidx.b (phopt only, probably impossible) -// idxaddr.b (phopt only, looks difficult) -// move.pri (eliminated in phopt) -// shl.c.pri (eliminated in phopt) -// shl.c.alt (eliminated in phopt) -// shr.c.pri (eliminated in phopt) -// shr.c.alt (eliminated in phopt) -// eq.c.alt (never) -// inc.alt (never) -// dec.alt (never) -// sdiv (never) -// nop (never in function bodies) -// -// Additionally, some opcodes which were supported in the earlier JIT are no -// longer supported because of the above: -// lref.pri/alt -// sref.pri/alt -// sign.pri/alt - -#define OPCODE_LIST(_) \ - _(NONE, "none") \ - _(LOAD_PRI, "load.pri") \ - _(LOAD_ALT, "load.alt") \ - _(LOAD_S_PRI, "load.s.pri") \ - _(LOAD_S_ALT, "load.s.alt") \ - _(UNGEN_LREF_PRI, "lref.pri") \ - _(UNGEN_LREF_ALT, "lref.alt") \ - _(LREF_S_PRI, "lref.s.pri") \ - _(LREF_S_ALT, "lref.s.alt") \ - _(LOAD_I, "load.i") \ - _(LODB_I, "lodb.i") \ - _(CONST_PRI, "const.pri") \ - _(CONST_ALT, "const.alt") \ - _(ADDR_PRI, "addr.pri") \ - _(ADDR_ALT, "addr.alt") \ - _(STOR_PRI, "stor.pri") \ - _(STOR_ALT, "stor.alt") \ - _(STOR_S_PRI, "stor.s.pri") \ - _(STOR_S_ALT, "stor.s.alt") \ - _(UNGEN_SREF_PRI, "sref.pri") \ - _(UNGEN_SREF_ALT, "sref.alt") \ - _(SREF_S_PRI, "sref.s.pri") \ - _(SREF_S_ALT, "sref.s.alt") \ - _(STOR_I, "stor.i") \ - _(STRB_I, "strb.i") \ - _(LIDX, "lidx") \ - _(LIDX_B, "lidx.b") \ - _(IDXADDR, "idxaddr") \ - _(IDXADDR_B, "idxaddr.b") \ - _(UNGEN_ALIGN_PRI,"align.pri") \ - _(UNGEN_ALIGN_ALT,"align.alt") \ - _(UNGEN_LCTRL, "lctrl") \ - _(UNGEN_SCTRL, "sctrl") \ - _(MOVE_PRI, "move.pri") \ - _(MOVE_ALT, "move.alt") \ - _(XCHG, "xchg") \ - _(PUSH_PRI, "push.pri") \ - _(PUSH_ALT, "push.alt") \ - _(UNGEN_PUSH_R, "push.r") \ - _(PUSH_C, "push.c") \ - _(PUSH, "push") \ - _(PUSH_S, "push.s") \ - _(POP_PRI, "pop.pri") \ - _(POP_ALT, "pop.alt") \ - _(STACK, "stack") \ - _(HEAP, "heap") \ - _(PROC, "proc") \ - _(UNGEN_RET, "ret") \ - _(RETN, "retn") \ - _(CALL, "call") \ - _(UNGEN_CALL_PRI, "call.pri") \ - _(JUMP, "jump") \ - _(UNGEN_JREL, "jrel") \ - _(JZER, "jzer") \ - _(JNZ, "jnz") \ - _(JEQ, "jeq") \ - _(JNEQ, "jneq") \ - _(UNGEN_JLESS, "jsless") \ - _(UNGEN_JLEQ, "jleq") \ - _(UNGEN_JGRTR, "jgrtr") \ - _(UNGEN_JGEQ, "jgeq") \ - _(JSLESS, "jsless") \ - _(JSLEQ, "jsleq") \ - _(JSGRTR, "jsgrtr") \ - _(JSGEQ, "jsgeq") \ - _(SHL, "shl") \ - _(SHR, "shr") \ - _(SSHR, "sshr") \ - _(SHL_C_PRI, "shl.c.pri") \ - _(SHL_C_ALT, "shl.c.alt") \ - _(SHR_C_PRI, "shr.c.pri") \ - _(SHR_C_ALT, "shr.c.alt") \ - _(SMUL, "smul") \ - _(SDIV, "sdiv") \ - _(SDIV_ALT, "sdiv.alt") \ - _(UNGEN_UMUL, "umul") \ - _(UNGEN_UDIV, "udiv") \ - _(UNGEN_UDIV_ALT, "udiv.alt") \ - _(ADD, "add") \ - _(SUB, "sub") \ - _(SUB_ALT, "sub.alt") \ - _(AND, "and") \ - _(OR, "or") \ - _(XOR, "xor") \ - _(NOT, "not") \ - _(NEG, "neg") \ - _(INVERT, "invert") \ - _(ADD_C, "add.c") \ - _(SMUL_C, "smul.c") \ - _(ZERO_PRI, "zero.pri") \ - _(ZERO_ALT, "zero.alt") \ - _(ZERO, "zero") \ - _(ZERO_S, "zero.s") \ - _(UNGEN_SIGN_PRI, "sign.pri") \ - _(UNGEN_SIGN_ALT, "sign.alt") \ - _(EQ, "eq") \ - _(NEQ, "neq") \ - _(UNGEN_LESS, "less") \ - _(UNGEN_LEQ, "leq") \ - _(UNGEN_GRTR, "grtr") \ - _(UNGEN_GEQ, "geq") \ - _(SLESS, "sless") \ - _(SLEQ, "sleq") \ - _(SGRTR, "sgrtr") \ - _(SGEQ, "sgeq") \ - _(EQ_C_PRI, "eq.c.pri") \ - _(EQ_C_ALT, "eq.c.alt") \ - _(INC_PRI, "inc.pri") \ - _(INC_ALT, "inc.alt") \ - _(INC, "inc") \ - _(INC_S, "inc.s") \ - _(INC_I, "inc.i") \ - _(DEC_PRI, "dec.pri") \ - _(DEC_ALT, "dec.alt") \ - _(DEC, "dec") \ - _(DEC_S, "dec.s") \ - _(DEC_I, "dec.i") \ - _(MOVS, "movs") \ - _(UNGEN_CMPS, "cmps") \ - _(FILL, "fill") \ - _(HALT, "halt") \ - _(BOUNDS, "bounds") \ - _(UNGEN_SYSREQ_PRI,"sysreq.pri") \ - _(SYSREQ_C, "sysreq.c") \ - _(UNGEN_FILE, "file") \ - _(UNGEN_LINE, "line") \ - _(UNGEN_SYMBOL, "symbol") \ - _(UNGEN_SRANGE, "srange") \ - _(UNGEN_JUMP_PRI, "jump.pri") \ - _(SWITCH, "switch") \ - _(CASETBL, "casetbl") \ - _(SWAP_PRI, "swap.pri") \ - _(SWAP_ALT, "swap.alt") \ - _(PUSH_ADR, "push.adr") \ - _(NOP, "nop") \ - _(SYSREQ_N, "sysreq.n") \ - _(UNGEN_SYMTAG, "symtag") \ - _(BREAK, "break") \ - _(PUSH2_C, "push2.c") \ - _(PUSH2, "push2") \ - _(PUSH2_S, "push2.s") \ - _(PUSH2_ADR, "push2.adr") \ - _(PUSH3_C, "push3.c") \ - _(PUSH3, "push3") \ - _(PUSH3_S, "push3.s") \ - _(PUSH3_ADR, "push3.adr") \ - _(PUSH4_C, "push4.c") \ - _(PUSH4, "push4") \ - _(PUSH4_S, "push4.s") \ - _(PUSH4_ADR, "push4.adr") \ - _(PUSH5_C, "push5.c") \ - _(PUSH5, "push5") \ - _(PUSH5_S, "push5.s") \ - _(PUSH5_ADR, "push5.adr") \ - _(LOAD_BOTH, "load.both") \ - _(LOAD_S_BOTH, "load.s.both") \ - _(CONST, "const") \ - _(CONST_S, "const.s") \ - _(UNGEN_SYSREQ_D, "sysreq.d") \ - _(UNGEB_SYSREQ_ND,"sysreq.nd") \ - _(TRACKER_PUSH_C, "trk.push.c") \ - _(TRACKER_POP_SETHEAP,"trk.pop") \ - _(GENARRAY, "genarray") \ - _(GENARRAY_Z, "genarray.z") \ - _(STRADJUST_PRI, "stradjust.pri") \ - _(UNGEN_STKADJUST,"stackadjust") \ - _(ENDPROC, "endproc") \ - _(UNGEN_LDGFN_PRI,"ldgfn.pri") \ - _(FABS, "fabs") \ - _(FLOAT, "float") \ - _(FLOATADD, "float.add") \ - _(FLOATSUB, "float.sub") \ - _(FLOATMUL, "float.mul") \ - _(FLOATDIV, "float.div") \ - _(RND_TO_NEAREST, "round") \ - _(RND_TO_FLOOR, "floor") \ - _(RND_TO_CEIL, "ceil") \ - _(RND_TO_ZERO, "rndtozero") \ - _(FLOATCMP, "float.cmp") \ - _(FLOAT_GT, "float.gt") \ - _(FLOAT_GE, "float.ge") \ - _(FLOAT_LT, "float.lt") \ - _(FLOAT_LE, "float.le") \ - _(FLOAT_NE, "float.ne") \ - _(FLOAT_EQ, "float.eq") \ - _(FLOAT_NOT, "float.not") - -enum OPCODE { -#define _(op, text) OP_##op, - OPCODE_LIST(_) -#undef _ - OPCODES_LAST -}; - -#define OPCODES_TOTAL (ucell_t)OPCODES_LAST - -} // namespace sp - -#endif // _INCLUDE_SPFILE_HEADERS_v1_opcodes_H diff --git a/sourcepawn/include/smx/smx-v1.h b/sourcepawn/include/smx/smx-v1.h deleted file mode 100644 index 7ea2392e..00000000 --- a/sourcepawn/include/smx/smx-v1.h +++ /dev/null @@ -1,209 +0,0 @@ -// vim: set sts=2 ts=8 sw=2 tw=99 et: -// ============================================================================= -// SourcePawn -// Copyright (C) 2004-2014 AlliedModders LLC. All rights reserved. -// ============================================================================= -// -// This program is free software; you can redistribute it and/or modify it under -// the terms of the GNU General Public License, version 3.0, as published by the -// Free Software Foundation. -// -// This program is distributed in the hope that it will be useful, but WITHOUT -// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -// FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -// details. -// -// You should have received a copy of the GNU General Public License along with -// this program. If not, see . -// -// As a special exception, AlliedModders LLC gives you permission to link the -// code of this program (as well as its derivative works) to "Half-Life 2," the -// "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software -// by the Valve Corporation. You must obey the GNU General Public License in -// all respects for all other code used. Additionally, AlliedModders LLC grants -// this exception to all derivative works. AlliedModders LLC defines further -// exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007), -// or . - -#ifndef _INCLUDE_SPFILE_HEADERS_v1_H -#define _INCLUDE_SPFILE_HEADERS_v1_H - -#include -#include -#include - -namespace sp { - -// These structures are byte-packed. -#if defined __GNUC__ -# pragma pack(1) -#else -# pragma pack(push) -# pragma pack(1) -#endif - -// (Obsolete) debug-information is present. -static const uint16_t CODEFLAG_DEBUG = 0x1; - -// The ".data" section. -typedef struct sp_file_data_s -{ - uint32_t datasize; /**< Size of data section in memory */ - uint32_t memsize; /**< Total mem required (includes data) */ - uint32_t data; /**< File offset to data (helper) */ -} sp_file_data_t; - -// The ".publics" section. -typedef struct sp_file_publics_s -{ - uint32_t address; /**< Address relative to code section */ - uint32_t name; /**< Index into nametable */ -} sp_file_publics_t; - -// The ".natives" section. -typedef struct sp_file_natives_s -{ - uint32_t name; /**< Index into nametable */ -} sp_file_natives_t; - -// The ".pubvars" section. -typedef struct sp_file_pubvars_s -{ - uint32_t address; /**< Address relative to the DAT section */ - uint32_t name; /**< Index into nametable */ -} sp_file_pubvars_t; - -// The ".tags" section. -typedef struct sp_file_tag_s -{ - uint32_t tag_id; /**< Tag ID from compiler */ - uint32_t name; /**< Index into nametable */ -} sp_file_tag_t; - -// The ".dbg.info" section. -typedef struct sp_fdbg_info_s -{ - uint32_t num_files; /**< number of files */ - uint32_t num_lines; /**< number of lines */ - uint32_t num_syms; /**< number of symbols */ - uint32_t num_arrays; /**< number of symbols which are arrays */ -} sp_fdbg_info_t; - -// The ".dbg.files" section. -typedef struct sp_fdbg_file_s -{ - uint32_t addr; /**< Address into code */ - uint32_t name; /**< Offset into debug nametable */ -} sp_fdbg_file_t; - -// The ".dbg.lines" section. -typedef struct sp_fdbg_line_s -{ - uint32_t addr; /**< Address into code */ - uint32_t line; /**< Line number */ -} sp_fdbg_line_t; - -static const uint8_t IDENT_VARIABLE = 1; // Scalar local variable. -static const uint8_t IDENT_REFERENCE = 2; // Reference to a scalar argument. -static const uint8_t IDENT_ARRAY = 3; // Array with known dimensions. -static const uint8_t IDENT_REFARRAY = 4; // Array with unknown dimensions. -static const uint8_t IDENT_FUNCTION = 9; // Symbolic function. -static const uint8_t IDENT_VARARGS = 11; // Variadic argument (...). - -// The ".dbg.symbols" table. -typedef struct sp_fdbg_symbol_s -{ - int32_t addr; /**< Address rel to DAT or stack frame */ - int16_t tagid; /**< Tag id */ - uint32_t codestart; /**< Start scope validity in code */ - uint32_t codeend; /**< End scope validity in code */ - uint8_t ident; /**< Variable type */ - uint8_t vclass; /**< Scope class (local vs global) */ - uint16_t dimcount; /**< Dimension count (for arrays) */ - uint32_t name; /**< Offset into debug nametable */ -} sp_fdbg_symbol_t; - -// Occurs after an fdbg_symbol entry, for each dimension. -typedef struct sp_fdbg_arraydim_s -{ - int16_t tagid; /**< Tag id */ - uint32_t size; /**< Size of dimension */ -} sp_fdbg_arraydim_t; - -// Typedef for the ".names" section. -typedef char * sp_file_nametab_t; - -// Header for the ".dbg.natives" section. It is followed by a number of -// sp_fdbg_native_t entries. -typedef struct sp_fdbg_ntvtab_s -{ - uint32_t num_entries; /**< Number of entries. */ -} sp_fdbg_ntvtab_t; - -// An entry in the .dbg.natives section. Each is followed by an -// sp_fdbg_ntvarg_t for each argument. -typedef struct sp_fdbg_native_s -{ - uint32_t index; /**< Native index in the plugin. */ - uint32_t name; /**< Offset into debug nametable. */ - int16_t tagid; /**< Return tag. */ - uint16_t nargs; /**< Number of formal arguments. */ -} sp_fdbg_native_t; - -static const uint8_t IDENT_NATIVE_VARARGS = 1; - -// Each entry is followed by an sp_fdbg_arraydim_t for each dimcount. -typedef struct sp_fdbg_ntvarg_s -{ - uint8_t ident; /**< Variable type */ - int16_t tagid; /**< Tag id */ - uint16_t dimcount; /**< Dimension count (for arrays) */ - uint32_t name; /**< Offset into debug nametable */ -} sp_fdbg_ntvarg_t; - -// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! -// DO NOT DEFINE NEW STRUCTURES BELOW. -// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! - -#if defined __GNUC__ -# pragma pack() /* reset default packing */ -#else -# pragma pack(pop) /* reset previous packing */ -#endif - -// The packing for files changed by accident for a small window of time, and -// some files may have unparsable debug information using sp_fdbg_arraydim_t or -// sp_fdbg_symbol_t. -// -// If the file version is >= 0x0102, all structures will be packed. If the -// file version is < 0x0101, and the ".dbg.natives" table is present, -// all structures will be packed. -// -// If the version is 0x0101 and ".dbg.natives" is not present, then you must -// use the unpacked versions of those structures below. There is an extremely -// small chance, if the plugin used no natives, that the packing is -// indeterminate. This case is unlikely to be interesting, but if such a file -// exists, the only solution is to re-parse if the data looks corrupt. - -typedef struct sp_u_fdbg_arraydim_s -{ - int16_t tagid; /**< Tag id */ - uint32_t size; /**< Size of dimension */ -} sp_u_fdbg_arraydim_t; - -typedef struct sp_u_fdbg_symbol_s -{ - int32_t addr; /**< Address rel to DAT or stack frame */ - int16_t tagid; /**< Tag id */ - uint32_t codestart; /**< Start scope validity in code */ - uint32_t codeend; /**< End scope validity in code */ - uint8_t ident; /**< Variable type */ - uint8_t vclass; /**< Scope class (local vs global) */ - uint16_t dimcount; /**< Dimension count (for arrays) */ - uint32_t name; /**< Offset into debug nametable */ -} sp_u_fdbg_symbol_t; - -} // namespace sp - -#endif //_INCLUDE_SPFILE_HEADERS_v1_H - diff --git a/sourcepawn/include/sp_typeutil.h b/sourcepawn/include/sp_typeutil.h deleted file mode 100644 index 78eb0f5a..00000000 --- a/sourcepawn/include/sp_typeutil.h +++ /dev/null @@ -1,65 +0,0 @@ -/** - * vim: set ts=4 : - * ============================================================================= - * SourcePawn - * Copyright (C) 2004-2008 AlliedModders LLC. All rights reserved. - * ============================================================================= - * - * This program is free software; you can redistribute it and/or modify it under - * the terms of the GNU General Public License, version 3.0, as published by the - * Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS - * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more - * details. - * - * You should have received a copy of the GNU General Public License along with - * this program. If not, see . - * - * As a special exception, AlliedModders LLC gives you permission to link the - * code of this program (as well as its derivative works) to "Half-Life 2," the - * "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software - * by the Valve Corporation. You must obey the GNU General Public License in - * all respects for all other code used. Additionally, AlliedModders LLC grants - * this exception to all derivative works. AlliedModders LLC defines further - * exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007), - * or . - * - * Version: $Id$ - */ - -#ifndef _INCLUDE_SOURCEPAWN_VM_TYPEUTIL_H_ -#define _INCLUDE_SOURCEPAWN_VM_TYPEUTIL_H_ - -/** - * @file sp_typeutil.h - * @brief Defines type utility functions. - */ - -#include "sp_vm_types.h" - -/** - * @brief Reinterpret-casts a float to a cell (requires -fno-strict-aliasing for GCC). - * - * @param val Float value. - * @return Cell typed version. - */ -inline cell_t sp_ftoc(float val) -{ - return *(cell_t *)&val; -} - -/** - * @brief Reinterpret-casts a cell to a float (requires -fno-strict-aliasing for GCC). - * - * @param val Cell-packed float value. - * @return Float typed version. - */ -inline float sp_ctof(cell_t val) -{ - return *(float *)&val; -} - -#endif //_INCLUDE_SOURCEPAWN_VM_TYPEUTIL_H_ - diff --git a/sourcepawn/include/sp_vm_api.h b/sourcepawn/include/sp_vm_api.h deleted file mode 100644 index 39f52b94..00000000 --- a/sourcepawn/include/sp_vm_api.h +++ /dev/null @@ -1,1618 +0,0 @@ -// vim: set ts=4 sw=4 tw=99 noet: -// -// Copyright (C) 2006-2015 AlliedModders LLC -// -// This file is part of SourcePawn. SourcePawn is free software: you can -// redistribute it and/or modify it under the terms of the GNU General Public -// License as published by the Free Software Foundation, either version 3 of -// the License, or (at your option) any later version. -// -// You should have received a copy of the GNU General Public License along with -// SourcePawn. If not, see http://www.gnu.org/licenses/. -// -#ifndef _INCLUDE_SOURCEPAWN_VM_API_H_ -#define _INCLUDE_SOURCEPAWN_VM_API_H_ - -/** - * @file sp_vm_api.h - * @brief Contains all of the object structures used in the SourcePawn API. - */ - -#include -#include -#include "sp_vm_types.h" - -/** SourcePawn Engine API Versions */ -#define SOURCEPAWN_ENGINE2_API_VERSION 0xA -#define SOURCEPAWN_API_VERSION 0x020A - -namespace SourceMod { - struct IdentityToken_t; -}; -namespace sp { - class Environment; -}; - -struct sp_context_s; -typedef struct sp_context_s sp_context_t; - -namespace SourcePawn -{ - class IVirtualMachine; - class IPluginRuntime; - class ISourcePawnEngine2; - class ISourcePawnEnvironment; - - /* Parameter flags */ - #define SM_PARAM_COPYBACK (1<<0) /**< Copy an array/reference back after call */ - - /* String parameter flags (separate from parameter flags) */ - #define SM_PARAM_STRING_UTF8 (1<<0) /**< String should be UTF-8 handled */ - #define SM_PARAM_STRING_COPY (1<<1) /**< String should be copied into the plugin */ - #define SM_PARAM_STRING_BINARY (1<<2) /**< String should be handled as binary data */ - - /** - * @brief Pseudo-NULL reference types. - */ - enum SP_NULL_TYPE - { - SP_NULL_VECTOR = 0, /**< Float[3] reference */ - SP_NULL_STRING = 1, /**< const String[1] reference */ - }; - - /** - * @brief Represents what a function needs to implement in order to be callable. - */ - class ICallable - { - public: - /** - * @brief Pushes a cell onto the current call. - * - * @param cell Parameter value to push. - * @return Error code, if any. - */ - virtual int PushCell(cell_t cell) =0; - - /** - * @brief Pushes a cell by reference onto the current call. - * NOTE: On Execute, the pointer passed will be modified if copyback is enabled. - * NOTE: By reference parameters are cached and thus are not read until execution. - * This means you cannot push a pointer, change it, and push it again and expect - * two different values to come out. - * - * @param cell Address containing parameter value to push. - * @param flags Copy-back flags. - * @return Error code, if any. - */ - virtual int PushCellByRef(cell_t *cell, int flags=SM_PARAM_COPYBACK) =0; - - /** - * @brief Pushes a float onto the current call. - * - * @param number Parameter value to push. - * @return Error code, if any. - */ - virtual int PushFloat(float number) =0; - - /** - * @brief Pushes a float onto the current call by reference. - * NOTE: On Execute, the pointer passed will be modified if copyback is enabled. - * NOTE: By reference parameters are cached and thus are not read until execution. - * This means you cannot push a pointer, change it, and push it again and expect - * two different values to come out. - * - * @param number Parameter value to push. - & @param flags Copy-back flags. - * @return Error code, if any. - */ - virtual int PushFloatByRef(float *number, int flags=SM_PARAM_COPYBACK) =0; - - /** - * @brief Pushes an array of cells onto the current call. - * - * On Execute, the pointer passed will be modified if non-NULL and copy-back - * is enabled. - * - * By reference parameters are cached and thus are not read until execution. - * This means you cannot push a pointer, change it, and push it again and expect - * two different values to come out. - * - * @param inarray Array to copy, NULL if no initial array should be copied. - * @param cells Number of cells to allocate and optionally read from the input array. - * @param flags Whether or not changes should be copied back to the input array. - * @return Error code, if any. - */ - virtual int PushArray(cell_t *inarray, unsigned int cells, int flags=0) =0; - - /** - * @brief Pushes a string onto the current call. - * - * @param string String to push. - * @return Error code, if any. - */ - virtual int PushString(const char *string) =0; - - /** - * @brief Pushes a string or string buffer. - * - * NOTE: On Execute, the pointer passed will be modified if copy-back is enabled. - * - * @param buffer Pointer to string buffer. - * @param length Length of buffer. - * @param sz_flags String flags. In copy mode, the string will be copied - * according to the handling (ascii, utf-8, binary, etc). - * @param cp_flags Copy-back flags. - * @return Error code, if any. - */ - virtual int PushStringEx(char *buffer, size_t length, int sz_flags, int cp_flags) =0; - - /** - * @brief Cancels a function call that is being pushed but not yet executed. - * This can be used be reset for CallFunction() use. - */ - virtual void Cancel() =0; - }; - - - /** - * @brief Encapsulates a function call in a plugin. - * - * NOTE: Function calls must be atomic to one execution context. - * NOTE: This object should not be deleted. It lives for the lifetime of the plugin. - */ - class IPluginFunction : public ICallable - { - public: - /** - * @brief Executes the function, resets the pushed parameter list, and - * performs any copybacks. - * - * The exception state is reset upon entering and leaving this - * function. Callers that want to propagate exceptions from Execute() - * should use Invoke(). ReportError is not preferred since it would - * lose any custom exception messages. - * - * @param result Pointer to store return value in. - * @return Error code, if any. - */ - virtual int Execute(cell_t *result) =0; - - /** - * @brief This function is deprecated. If invoked, it reports an error. - * - * @param params Unused. - * @param num_params Unused. - * @param result Unused. - * @return SP_ERROR_ABORTED. - */ - virtual int CallFunction(const cell_t *params, unsigned int num_params, cell_t *result) =0; - - /** - * @brief Deprecated, do not use. - * - * @return GetDefaultContext() of parent runtime. - */ - virtual IPluginContext *GetParentContext() =0; - - /** - * @brief Returns whether the parent plugin is paused. - * - * @return True if runnable, false otherwise. - */ - virtual bool IsRunnable() =0; - - /** - * @brief Returns the function ID of this function. - * - * Note: This was added in API version 4. - * - * @return Function id. - */ - virtual funcid_t GetFunctionID() =0; - - /** - * @brief This function is deprecated. If invoked, it reports an error. - * - * @param ctx Unused. - * @param result Unused. - * @return SP_ERROR_ABORTED. - */ - virtual int Execute2(IPluginContext *ctx, cell_t *result) =0; - - /** - * @brief This function is deprecated. If invoked, it reports an error. - * - * @param ctx Unused. - * @param params Unused. - * @param num_params Unused. - * @param result Unused. - * @return SP_ERROR_ABORTED. - */ - virtual int CallFunction2(IPluginContext *ctx, - const cell_t *params, - unsigned int num_params, - cell_t *result) =0; - - /** - * @brief Returns parent plugin's runtime - * - * @return IPluginRuntime pointer. - */ - virtual IPluginRuntime *GetParentRuntime() =0; - - /** - * @brief Executes the function, resets the pushed parameter list, and - * performs any copybacks. - * - * Unlike Execute(), this does not reset the exception state. It is - * illegal to call Invoke() while an exception is unhandled. If it - * returns false, an exception has been thrown, and must either be - * handled via ExceptionHandler or propagated to its caller. - * - * @param result Pointer to store return value in. - * @return True on success, false on error. - */ - virtual bool Invoke(cell_t *rval = nullptr) = 0; - }; - - - /** - * @brief Interface to managing a debug context at runtime. - */ - class IPluginDebugInfo - { - public: - /** - * @brief Given a code pointer, finds the file it is associated with. - * - * @param addr Code address offset. - * @param filename Pointer to store filename pointer in. - */ - virtual int LookupFile(ucell_t addr, const char **filename) =0; - - /** - * @brief Given a code pointer, finds the function it is associated with. - * - * @param addr Code address offset. - * @param name Pointer to store function name pointer in. - */ - virtual int LookupFunction(ucell_t addr, const char **name) =0; - - /** - * @brief Given a code pointer, finds the line it is associated with. - * - * @param addr Code address offset. - * @param line Pointer to store line number in. - */ - virtual int LookupLine(ucell_t addr, uint32_t *line) =0; - }; - - class ICompilation; - - /** - * @brief Interface to managing a runtime plugin. - */ - class IPluginRuntime - { - public: - /** - * @brief Virtual destructor (you may call delete). - */ - virtual ~IPluginRuntime() - { - } - - /** - * @brief Returns debug info. - * - * @return IPluginDebugInfo, or NULL if no debug info found. - */ - virtual IPluginDebugInfo *GetDebugInfo() =0; - - /** - * @brief Finds a native by name. - * - * @param name Name of native. - * @param index Optionally filled with native index number. - */ - virtual int FindNativeByName(const char *name, uint32_t *index) =0; - - /** - * @brief Deprecated, does nothing. - * - * @param index Unused. - * @param native Unused. - * @return Returns SP_ERROR_PARAM. - */ - virtual int GetNativeByIndex(uint32_t index, sp_native_t **native) =0; - - /** - * @brief Gets the number of natives. - * - * @return Filled with the number of natives. - */ - virtual uint32_t GetNativesNum() =0; - - /** - * @brief Finds a public function by name. - * - * @param name Name of public - * @param index Optionally filled with public index number. - */ - virtual int FindPublicByName(const char *name, uint32_t *index) =0; - - /** - * @brief Gets public function info by index. - * - * @param index Public function index number. - * @param publicptr Optionally filled with pointer to public structure. - */ - virtual int GetPublicByIndex(uint32_t index, sp_public_t **publicptr) =0; - - /** - * @brief Gets the number of public functions. - * - * @return Filled with the number of public functions. - */ - virtual uint32_t GetPublicsNum() =0; - - /** - * @brief Gets public variable info by index. - * - * @param index Public variable index number. - * @param pubvar Optionally filled with pointer to pubvar structure. - */ - virtual int GetPubvarByIndex(uint32_t index, sp_pubvar_t **pubvar) =0; - - /** - * @brief Finds a public variable by name. - * - * @param name Name of pubvar - * @param index Optionally filled with pubvar index number. - */ - virtual int FindPubvarByName(const char *name, uint32_t *index) =0; - - /** - * @brief Gets the addresses of a public variable. - * - * @param index Index of public variable. - * @param local_addr Address to store local address in. - * @param phys_addr Address to store physically relocated in. - */ - virtual int GetPubvarAddrs(uint32_t index, cell_t *local_addr, cell_t **phys_addr) =0; - - /** - * @brief Returns the number of public variables. - * - * @return Number of public variables. - */ - virtual uint32_t GetPubVarsNum() =0; - - /** - * @brief Returns a function by name. - * - * @param public_name Name of the function. - * @return A new IPluginFunction pointer, NULL if not found. - */ - virtual IPluginFunction *GetFunctionByName(const char *public_name) =0; - - /** - * @brief Returns a function by its id. - * - * @param func_id Function ID. - * @return A new IPluginFunction pointer, NULL if not found. - */ - virtual IPluginFunction *GetFunctionById(funcid_t func_id) =0; - - /** - * @brief Returns the default context. The default context - * should not be destroyed. - * - * @return Default context pointer. - */ - virtual IPluginContext *GetDefaultContext() =0; - - /** - * @brief Returns true if the plugin is in debug mode. - * - * @return True if in debug mode, false otherwise. - */ - virtual bool IsDebugging() =0; - - /** - * @brief If |co| is non-NULL, destroys |co|. No other action is taken. - * - * @return Returns SP_ERROR_NONE. - */ - virtual int ApplyCompilationOptions(ICompilation *co) =0; - - /** - * @brief Sets whether or not the plugin is paused (cannot be run). - * - * @param pause Pause state. - */ - virtual void SetPauseState(bool paused) =0; - - /** - * @brief Returns whether or not the plugin is paused (runnable). - * - * @return Pause state (true = paused, false = not). - */ - virtual bool IsPaused() =0; - - /** - * @brief Returns the estimated memory usage of this plugin. - * - * @return Memory usage, in bytes. - */ - virtual size_t GetMemUsage() =0; - - /** - * @brief Returns the MD5 hash of the plugin's P-Code. - * - * @return 16-byte buffer with MD5 hash of the plugin's P-Code. - */ - virtual unsigned char *GetCodeHash() =0; - - /** - * @brief Returns the MD5 hash of the plugin's Data. - * - * @return 16-byte buffer with MD5 hash of the plugin's Data. - */ - virtual unsigned char *GetDataHash() =0; - - /** - * @brief Update the native binding at the given index. - * - * @param pfn Native function pointer. - * @param flags Native flags. - * @param user User data pointer. - */ - virtual int UpdateNativeBinding(uint32_t index, SPVM_NATIVE_FUNC pfn, uint32_t flags, void *data) = 0; - - /** - * @brief Returns the native at the given index. - * - * @param index Native index. - * @return Native pointer, or NULL on failure. - */ - virtual const sp_native_t *GetNative(uint32_t index) = 0; - - /** - * @brief Return the file or location this plugin was loaded from. - */ - virtual const char *GetFilename() = 0; - }; - - /** - * @brief Interface to managing a context at runtime. - */ - class IPluginContext - { - public: - /** Virtual destructor */ - virtual ~IPluginContext() { }; - public: - /** - * @brief Deprecated, does nothing. - * - * @return NULL. - */ - virtual IVirtualMachine *GetVirtualMachine() =0; - - /** - * @brief Deprecated, do not use. - * - * Returns the pointer of this object, casted to an opaque structure. - * - * @return Returns this. - */ - virtual sp_context_t *GetContext() =0; - - /** - * @brief Returns true if the plugin is in debug mode. - * - * @return True if in debug mode, false otherwise. - */ - virtual bool IsDebugging() =0; - - /** - * @brief Deprecated, does nothing. - * - * @param newpfn Unused. - * @param oldpfn Unused. - */ - virtual int SetDebugBreak(void *newpfn, void *oldpfn) =0; - - /** - * @brief Deprecated, do not use. - * - * @return NULL. - */ - virtual IPluginDebugInfo *GetDebugInfo() =0; - - /** - * @brief Allocates memory on the secondary stack of a plugin. - * Note that although called a heap, it is in fact a stack. - * - * @param cells Number of cells to allocate. - * @param local_addr Will be filled with data offset to heap. - * @param phys_addr Physical address to heap memory. - */ - virtual int HeapAlloc(unsigned int cells, cell_t *local_addr, cell_t **phys_addr) =0; - - /** - * @brief Pops a heap address off the heap stack. Use this to free memory allocated with - * SP_HeapAlloc(). - * Note that in SourcePawn, the heap is in fact a bottom-up stack. Deallocations - * with this native should be performed in precisely the REVERSE order. - * - * @param local_addr Local address to free. - */ - virtual int HeapPop(cell_t local_addr) =0; - - /** - * @brief Releases a heap address using a different method than SP_HeapPop(). - * This allows you to release in any order. However, if you allocate N - * objects, release only some of them, then begin allocating again, - * you cannot go back and starting freeing the originals. - * In other words, for each chain of allocations, if you start deallocating, - * then allocating more in a chain, you must only deallocate from the current - * allocation chain. This is basically HeapPop() except on a larger scale. - * - * @param local_addr Local address to free. - */ - virtual int HeapRelease(cell_t local_addr) =0; - - /** - * @brief Deprecated, use IPluginRuntime instead. - * - * @param name Name of native. - * @param index Optionally filled with native index number. - */ - virtual int FindNativeByName(const char *name, uint32_t *index) =0; - - /** - * @brief Deprecated, does nothing. - * - * @param index Unused. - * @param native Unused. - * @return Returns SP_ERROR_PARAM. - */ - virtual int GetNativeByIndex(uint32_t index, sp_native_t **native) =0; - - /** - * @brief Deprecated, use IPluginRuntime instead. - * - * @return Filled with the number of natives. - */ - virtual uint32_t GetNativesNum() =0; - - /** - * @brief Deprecated, use IPluginRuntime instead. - * - * @param name Name of public - * @param index Optionally filled with public index number. - */ - virtual int FindPublicByName(const char *name, uint32_t *index) =0; - - /** - * @brief Deprecated, use IPluginRuntime instead. - * - * @param index Public function index number. - * @param publicptr Optionally filled with pointer to public structure. - */ - virtual int GetPublicByIndex(uint32_t index, sp_public_t **publicptr) =0; - - /** - * @brief Deprecated, use IPluginRuntime instead. - * - * @return Filled with the number of public functions. - */ - virtual uint32_t GetPublicsNum() =0; - - /** - * @brief Deprecated, use IPluginRuntime instead. - * - * @param index Public variable index number. - * @param pubvar Optionally filled with pointer to pubvar structure. - */ - virtual int GetPubvarByIndex(uint32_t index, sp_pubvar_t **pubvar) =0; - - /** - * @brief Deprecated, use IPluginRuntime instead. - * - * @param name Name of pubvar - * @param index Optionally filled with pubvar index number. - */ - virtual int FindPubvarByName(const char *name, uint32_t *index) =0; - - /** - * @brief Deprecated, use IPluginRuntime instead. - * - * @param index Index of public variable. - * @param local_addr Address to store local address in. - * @param phys_addr Address to store physically relocated in. - */ - virtual int GetPubvarAddrs(uint32_t index, cell_t *local_addr, cell_t **phys_addr) =0; - - /** - * @brief Deprecated, use IPluginRuntime instead. - * - * @return Number of public variables. - */ - virtual uint32_t GetPubVarsNum() =0; - - /** - * @brief Converts a plugin reference to a physical address - * - * @param local_addr Local address in plugin. - * @param phys_addr Optionally filled with relocated physical address. - */ - virtual int LocalToPhysAddr(cell_t local_addr, cell_t **phys_addr) =0; - - /** - * @brief Converts a local address to a physical string. - * - * @param local_addr Local address in plugin. - * @param addr Destination output pointer. - */ - virtual int LocalToString(cell_t local_addr, char **addr) =0; - - /** - * @brief Converts a physical string to a local address. - * - * @param local_addr Local address in plugin. - * @param bytes Number of chars to write, including NULL terminator. - * @param source Source string to copy. - */ - virtual int StringToLocal(cell_t local_addr, size_t bytes, const char *source) =0; - - /** - * @brief Converts a physical UTF-8 string to a local address. - * This function is the same as the ANSI version, except it will copy the maximum number - * of characters possible without accidentally chopping a multi-byte character. - * - * @param local_addr Local address in plugin. - * @param maxbytes Number of bytes to write, including NULL terminator. - * @param source Source string to copy. - * @param wrtnbytes Optionally set to the number of actual bytes written. - */ - virtual int StringToLocalUTF8(cell_t local_addr, - size_t maxbytes, - const char *source, - size_t *wrtnbytes) =0; - - /** - * @brief Deprecated, does nothing. - * - * @param value Unused. - */ - virtual int PushCell(cell_t value) =0; - - /** - * @brief Deprecated, does nothing. - * - * @param local_addr Unused. - * @param phys_addr Unused. - * @param array Unused. - * @param numcells Unused. - */ - virtual int PushCellArray(cell_t *local_addr, cell_t **phys_addr, cell_t array[], unsigned int numcells) =0; - - /** - * @brief Deprecated, does nothing. - * - * @param local_addr Unused. - * @param phys_addr Unused. - * @param string Unused. - */ - virtual int PushString(cell_t *local_addr, char **phys_addr, const char *string) =0; - - /** - * @brief Deprecated, does nothing. - * - * @param array Unused. - * @param numcells Unused. - */ - virtual int PushCellsFromArray(cell_t array[], unsigned int numcells) =0; - - /** - * @brief Deprecated, does nothing. - * - * @param natives Deprecated; do not use. - * @param num Deprecated; do not use. - * @param overwrite Deprecated; do not use. - */ - virtual int BindNatives(const sp_nativeinfo_t *natives, unsigned int num, int overwrite) =0; - - /** - * @brief Deprecated, does nothing. - * - * @param native Deprecated; do not use. - */ - virtual int BindNative(const sp_nativeinfo_t *native) =0; - - /** - * @brief Deprecated, does nothing. - * - * @param native Unused. - */ - virtual int BindNativeToAny(SPVM_NATIVE_FUNC native) =0; - - /** - * @brief Deprecated, does nothing. - * - * @param code_addr Unused. - * @param result Unused. - * @return SP_ERROR_ABORTED. - */ - virtual int Execute(uint32_t code_addr, cell_t *result) =0; - - /** - * @brief Throws a error and halts any current execution. - * - * This function is deprecated. Use ReportError() instead. - * - * @param error The error number to set. - * @param msg Custom error message format. NULL to use default. - * @param ... Message format arguments, if any. - * @return 0 for convenience. - */ - virtual cell_t ThrowNativeErrorEx(int error, const char *msg, ...) =0; - - /** - * @brief Throws a generic native error and halts any current execution. - * - * This function is deprecated. Use ReportError() instead. - * - * @param msg Custom error message format. NULL to set no message. - * @param ... Message format arguments, if any. - * @return 0 for convenience. - */ - virtual cell_t ThrowNativeError(const char *msg, ...) =0; - - /** - * @brief Returns a function by name. - * - * @param public_name Name of the function. - * @return A new IPluginFunction pointer, NULL if not found. - */ - virtual IPluginFunction *GetFunctionByName(const char *public_name) =0; - - /** - * @brief Returns a function by its id. - * - * @param func_id Function ID. - * @return A new IPluginFunction pointer, NULL if not found. - */ - virtual IPluginFunction *GetFunctionById(funcid_t func_id) =0; - - /** - * @brief Returns the identity token for this context. - * - * Note: This is a compatibility shim and is the same as GetKey(1). - * - * @return Identity token. - */ - virtual SourceMod::IdentityToken_t *GetIdentity() =0; - - /** - * @brief Returns a NULL reference based on one of the available NULL - * reference types. - * - * @param type NULL reference type. - * @return cell_t address to compare to. - */ - virtual cell_t *GetNullRef(SP_NULL_TYPE type) =0; - - /** - * @brief Converts a local address to a physical string, and allows - * for NULL_STRING to be set. - * - * @param local_addr Local address in plugin. - * @param addr Destination output pointer. - */ - virtual int LocalToStringNULL(cell_t local_addr, char **addr) =0; - - /** - * @brief Deprecated; do not use. - * - * @param index Deprecated; do not use. - * @param native Deprecated; do not use. - */ - virtual int BindNativeToIndex(uint32_t index, SPVM_NATIVE_FUNC native) =0; - - /** - * @brief Returns if there is currently an execution in progress. - * - * @return True if in exec, false otherwise. - */ - virtual bool IsInExec() =0; - - /** - * @brief Returns the parent runtime of a context. - * - * @return Parent runtime. - */ - virtual IPluginRuntime *GetRuntime() =0; - - /** - * @brief This function is deprecated. If invoked, it reports an error. - * - * @param function Unused. - * @param params Unused. - * @param num_params Unused. - * @param result Unused. - * @return SP_ERROR_ABORTED. - */ - virtual int Execute2(IPluginFunction *function, - const cell_t *params, - unsigned int num_params, - cell_t *result) =0; - - /** - * @brief Returns whether a context is in an error state. - * - * This function is deprecated. Use DetectExceptions instead. - * - * This should only be used inside natives to determine whether - * a prior call failed. The return value should only be compared - * against SP_ERROR_NONE. - */ - virtual int GetLastNativeError() =0; - - /** - * @brief Returns the local parameter stack, starting from the - * cell that contains the number of parameters passed. - * - * Local parameters are the parameters passed to the function - * from which a native was called (and thus this can only be - * called inside a native). - * - * @return Parameter stack. - */ - virtual cell_t *GetLocalParams() =0; - - /** - * @brief Sets a local "key" that can be used for fast lookup. - * - * Only the "owner" of the context should be setting this. - * - * @param key Key number (values allowed: 1 through 4). - * @param value Pointer value. - */ - virtual void SetKey(int k, void *value) =0; - - /** - * @brief Retrieves a previously set "key." - * - * @param key Key number (values allowed: 1 through 4). - * @param value Pointer to store value. - * @return True on success, false on failure. - */ - virtual bool GetKey(int k, void **value) =0; - - /** - * @brief If an exception is pending, this removes the exception. It - * is deprecated and should not be used. - */ - virtual void ClearLastNativeError() =0; - - /** - * @brief Return a pointer to the ISourcePawnEngine2 that is active. - * This is a convenience function. - * - * @return API pointer. - */ - virtual ISourcePawnEngine2 *APIv2() = 0; - - /** - * @brief Report an error. - * - * @param message Error message format. - * @param ... Formatting arguments. - */ - virtual void ReportError(const char *fmt, ...) = 0; - - /** - * @brief Report an error with variadic arguments. - * - * @param message Error message format. - * @param ap Formatting arguments. - */ - virtual void ReportErrorVA(const char *fmt, va_list ap) = 0; - - /** - * @brief Report a fatal error. Fatal errors cannot be caught by any - * exception handler. - * - * @param message Error message format. - * @param ... Formatting arguments. - */ - virtual void ReportFatalError(const char *fmt, ...) = 0; - - /** - * @brief Report a fatal error with variadic arguments. Fatal errors - * cannot be caught by any exception handler. - * - * @param message Error message format. - * @param ap Formatting arguments. - */ - virtual void ReportFatalErrorVA(const char *fmt, va_list ap) = 0; - - /** - * @brief Report an error by its builtin number. - * - * @param number Error number. - */ - virtual void ReportErrorNumber(int error) = 0; - }; - - /** - * @brief Removed. - */ - class IContextTrace; - - /** - * @brief Information about a reported error. - */ - class IErrorReport - { - public: - /** - * @brief Return the message of the error report. - * - * @return Message string. - */ - virtual const char *Message() const = 0; - - /** - * @brief True if the error is fatal and cannot be handled (though - * reporting can be suppressed). - * - * @return True if fatal, false otherwise. - */ - virtual bool IsFatal() const = 0; - - /** - * @brief Return the plugin context that caused the error. - * - * @return Plugin context. - */ - virtual IPluginContext *Context() const = 0; - }; - - /** - * @brief Allows inspecting the stack frames of the SourcePawn environment. - * - * Invoking VM functions while iterating frames will cause the iterator - * to become corrupt. - * - * Frames iterate in most-recent to least-recent order. - */ - class IFrameIterator - { - public: - /** - * @brief Returns whether or not there are more frames to read. - * - * @return True if there are more frames to read, false otherwise. - */ - virtual bool Done() const = 0; - - /** - * @brief Advances to the next frame. - * - * Note that the iterator starts at either a valid frame or no frame. - */ - virtual void Next() = 0; - - /** - * @brief Resets the iterator to the top of the stack. - */ - virtual void Reset() = 0; - - /** - * @brief Returns the context owning the current frame, if any. - * - * @return Context, or null. - */ - virtual IPluginContext *Context() const = 0; - - /** - * @brief Returns whether or not the current frame is a native frame. If it - * is, line numbers and file paths are not available. - * - * @return True if a native frame, false otherwise. - */ - virtual bool IsNativeFrame() const = 0; - - /** - * @brief Returns true if the frame is a scripted frame. - * - * @return True if a scripted frame, false otherwise. - */ - virtual bool IsScriptedFrame() const = 0; - - /** - * @brief Returns the line number of the current frame, or 0 if none is - * available. - * - * @return Line number on success, 0 on failure. - */ - virtual unsigned LineNumber() const = 0; - - /** - * @brief Returns the function name of the current frame, or null if - * none could be computed. - * - * @return Function name on success, null on failure. - */ - virtual const char *FunctionName() const = 0; - - /** - * @brief Returns the file path of the function of the current frame, - * or none could be computed. - * - * @return File path on success, null on failure. - */ - virtual const char *FilePath() const = 0; - }; - - /** - * @brief Provides callbacks for debug information. - */ - class IDebugListener - { - public: - /** - * @brief No longer invoked. - * - * @param ctx Unused. - * @param error Unused. - */ - virtual void OnContextExecuteError(IPluginContext *ctx, IContextTrace *error) - {} - - /** - * @brief Called on debug spew. - * - * @param msg Message text. - * @param fmt Message formatting arguments (printf-style). - */ - virtual void OnDebugSpew(const char *msg, ...) =0; - - /** - * @brief Called when an error is reported and no exception - * handler was available. - * - * @param report Error report object. - * @param iter Stack frame iterator. - */ - virtual void ReportError(const IErrorReport &report, IFrameIterator &iter) = 0; - }; - - /** - * @brief Removed. - */ - class IProfiler; - - /** - * @brief Encapsulates a profiling tool that may be attached to SourcePawn. - */ - class IProfilingTool - { - public: - /** - * @brief Return the name of the profiling tool. - * - * @return Profiling tool name. - */ - virtual const char *Name() = 0; - - /** - * @brief Description of the profiler. - * - * @return Description. - */ - virtual const char *Description() = 0; - - /** - * @brief Called to render help text. - * - * @param render Function to render one line of text. - */ - virtual void RenderHelp(void (*render)(const char *fmt, ...)) = 0; - - /** - * @brief Initiate a start command. - * - * Initiate start commands through a profiling tool, returning whether - * or not the command is supported. If starting, SourceMod will generate - * events even if it cannot signal the external profiler. - */ - virtual bool Start() = 0; - - /** - * @brief Initiate a stop command. - * - * @param render Function to render any help messages. - */ - virtual void Stop(void (*render)(const char *fmt, ...)) = 0; - - /** - * @brief Dump profiling information. - * - * Informs the profiling tool to dump any current profiling information - * it has accumulated. The format and location of the output is profiling - * tool specific. - */ - virtual void Dump() = 0; - - /** - * @brief Returns whether or not the profiler is currently profiling. - * - * @return True if active, false otherwise. - */ - virtual bool IsActive() = 0; - - /** - * @brief Returns whether the profiler is attached. - * - * @return True if attached, false otherwise. - */ - virtual bool IsAttached() = 0; - - /** - * @brief Enters the scope of an event. - * - * LeaveScope() mus be called exactly once for each call to EnterScope(). - * - * @param group A named budget group, or NULL for the default. - * @param name Event name. - */ - virtual void EnterScope(const char *group, const char *name) = 0; - - /** - * @brief Leave a profiling scope. This must be called exactly once for - * each call to EnterScope(). - */ - virtual void LeaveScope() = 0; - }; - - struct sp_plugin_s; - typedef struct sp_plugin_s sp_plugin_t; - - /** - * @brief Contains helper functions used by VMs and the host app - */ - class ISourcePawnEngine - { - public: - /** - * @brief Deprecated. Does nothing. - */ - virtual sp_plugin_t *LoadFromFilePointer(FILE *fp, int *err) =0; - - /** - * @brief Deprecated. Does nothing. - */ - virtual sp_plugin_t *LoadFromMemory(void *base, sp_plugin_t *plugin, int *err) =0; - - /** - * @brief Deprecated. Does nothing. - */ - virtual int FreeFromMemory(sp_plugin_t *plugin) =0; - - /** - * @brief Allocates large blocks of temporary memory. - * - * @param size Size of memory to allocate. - * @return Pointer to memory, NULL if allocation failed. - */ - virtual void *BaseAlloc(size_t size) =0; - - /** - * @brief Frees memory allocated with BaseAlloc. - * - * @param memory Memory address to free. - */ - virtual void BaseFree(void *memory) =0; - - /** - * @brief Allocates executable memory. - * @deprecated Use AllocPageMemory() - * - * @param size Size of memory to allocate. - * @return Pointer to memory, NULL if allocation failed. - */ - virtual void *ExecAlloc(size_t size) =0; - - /** - * @brief Frees executable memory. - * @deprecated Use FreePageMemory() - * - * @param address Address to free. - */ - virtual void ExecFree(void *address) =0; - - /** - * @brief Sets the debug listener. - * - * This should be called once on application startup. It is - * not considered part of the userland API and may change at any time. - * - * @param listener Pointer to an IDebugListener. - * @return Old IDebugListener, or NULL if none. - */ - virtual IDebugListener *SetDebugListener(IDebugListener *listener) =0; - - /** - * @brief Deprecated. Does nothing. - */ - virtual unsigned int GetContextCallCount() =0; - - /** - * @brief Returns the engine API version. - * - * @return Engine API version. - */ - virtual unsigned int GetEngineAPIVersion() =0; - - /** - * @brief Allocates executable memory. - * - * @param size Size of memory to allocate. - * @return Pointer to memory, NULL if allocation failed. - */ - virtual void *AllocatePageMemory(size_t size) =0; - - /** - * @brief Sets the input memory permissions to read+write. - * - * @param ptr Memory block. - */ - virtual void SetReadWrite(void *ptr) =0; - - /** - * @brief Sets the input memory permissions to read+execute. - * - * @param ptr Memory block. - */ - virtual void SetReadExecute(void *ptr) =0; - - /** - * @brief Frees executable memory. - * - * @param ptr Address to free. - */ - virtual void FreePageMemory(void *ptr) =0; - }; - - class ExceptionHandler; - - /** - * @brief Outlines the interface a Virtual Machine (JIT) must expose - */ - class ISourcePawnEngine2 - { - public: - /** - * @brief Returns the second engine API version. - * - * @return API version. - */ - virtual unsigned int GetAPIVersion() =0; - - /** - * @brief Returns the string name of a VM implementation. - */ - virtual const char *GetEngineName() =0; - - /** - * @brief Returns a version string. - * - * @return Versioning string. - */ - virtual const char *GetVersionString() =0; - - /** - * @brief Deprecated. Returns null. - * - * @return Null. - */ - virtual ICompilation *StartCompilation() =0; - - /** - * @brief Loads a plugin from disk. - * - * If a compilation object is supplied, it is destroyed upon - * the function's return. - * - * @param co Must be NULL. - * @param file Path to the file to compile. - * @param err Error code (filled on failure); required. - * @return New runtime pointer, or NULL on failure. - */ - virtual IPluginRuntime *LoadPlugin(ICompilation *co, const char *file, int *err) =0; - - /** - * @brief Creates a fake native and binds it to a general callback function. - * - * @param callback Callback function to bind the native to. - * @param pData Private data to pass to the callback when the native is invoked. - * @return A new fake native function as a wrapper around the callback. - */ - virtual SPVM_NATIVE_FUNC CreateFakeNative(SPVM_FAKENATIVE_FUNC callback, void *pData) =0; - - /** - * @brief Destroys a fake native function wrapper. - * - * @param func Pointer to the fake native created by CreateFakeNative. - */ - virtual void DestroyFakeNative(SPVM_NATIVE_FUNC func) =0; - - /** - * @brief Sets the debug listener. - * - * This should be called once on application startup. It is - * not considered part of the userland API and may change at any time. - * - * @param listener Pointer to an IDebugListener. - * @return Old IDebugListener, or NULL if none. - */ - virtual IDebugListener *SetDebugListener(IDebugListener *listener) =0; - - /** - * @brief Deprecated. - * - * @param profiler Deprecated. - */ - virtual void SetProfiler(IProfiler *profiler) =0; - - /** - * @brief Returns the string representation of an error message. - * - * This function is deprecated and should not be used. The exception - * handling API should be used instead. - * - * @param err Error code. - * @return Error string, or NULL if not found. - */ - virtual const char *GetErrorString(int err) =0; - - /** - * @brief Deprecated. Does nothing. - */ - virtual bool Initialize() =0; - - /** - * @brief Deprecated. Does nothing. - */ - virtual void Shutdown() =0; - - /** - * @brief Creates an empty plugin with a blob of memory. - * - * @param name Name, for debugging (NULL for anonymous). - * @param bytes Number of bytes of memory (hea+stk). - * @return New runtime, or NULL if not enough memory. - */ - virtual IPluginRuntime *CreateEmptyRuntime(const char *name, uint32_t memory) =0; - - /** - * @brief Initiates the watchdog timer with the specified timeout - * length. This cannot be called more than once. - * - * @param timeout Timeout, in ms. - * @return True on success, false on failure. - */ - virtual bool InstallWatchdogTimer(size_t timeout_ms) =0; - - /** - * @brief Sets whether the JIT is enabled or disabled. - * - * @param enabled True or false to enable or disable. - * @return True if successful, false otherwise. - */ - virtual bool SetJitEnabled(bool enabled) =0; - - /** - * @brief Returns whether the JIT is enabled. - * - * @return True if the JIT is enabled, false otherwise. - */ - virtual bool IsJitEnabled() =0; - - /** - * @brief Enables profiling. SetProfilingTool() must have been called. - * - * Note that this does not activate the profiling tool. It only enables - * notifications to the profiling tool. SourcePawn will send events to - * the profiling tool even if the tool itself is reported as inactive. - */ - virtual void EnableProfiling() = 0; - - /** - * @brief Disables profiling. - */ - virtual void DisableProfiling() = 0; - - /** - * @brief Sets the profiling tool. - * - * @param tool Profiling tool. - */ - virtual void SetProfilingTool(IProfilingTool *tool) =0; - - /** - * @brief Loads a plugin from disk. - * - * @param file Path to the file to compile. - * @param errpr Buffer to store an error message (optional). - * @param maxlength Maximum length of the error buffer. - * @return New runtime pointer, or NULL on failure. - */ - virtual IPluginRuntime *LoadBinaryFromFile(const char *file, char *error, size_t maxlength) = 0; - - /** - * @brief Returns the environment. - */ - virtual ISourcePawnEnvironment *Environment() = 0; - }; - - // @brief This class is the v3 API for SourcePawn. It provides access to - // the original v1 and v2 APIs as well. - class ISourcePawnEnvironment - { - public: - // The Environment must be freed with the delete keyword. This - // automatically calls Shutdown(). - virtual ~ISourcePawnEnvironment() - {} - - // @brief Return the API version. - virtual int ApiVersion() = 0; - - // @brief Return a pointer to the v1 API. - virtual ISourcePawnEngine *APIv1() = 0; - - // @brief Return a pointer to the v2 API. - virtual ISourcePawnEngine2 *APIv2() = 0; - - // @brief Destroy the environment, releasing all resources and freeing - // all plugin memory. This should not be called while plugins have - // active code running on the stack. - virtual void Shutdown() = 0; - - // @brief Enters an exception handling scope. This is intended to be - // used on the stack and must have a corresponding call to - // LeaveExceptionHandlingScope. When in an exception handling scope, - // exceptions are not immediately reported. Instead the caller is - // responsible for propagation them or clearing them. - virtual void EnterExceptionHandlingScope(ExceptionHandler *handler) = 0; - - // @brief Leaves the most recent exception handling scope. The handler - // is provided as a sanity check. - virtual void LeaveExceptionHandlingScope(ExceptionHandler *handler) = 0; - - // @brief Returns whether or not an exception is currently pending. - virtual bool HasPendingException(const ExceptionHandler *handler) = 0; - - // @brief Returns the message of the pending exception. - virtual const char *GetPendingExceptionMessage(const ExceptionHandler *handler) = 0; - }; - - // @brief This class is the entry-point to using SourcePawn from a DLL. - class ISourcePawnFactory - { - public: - // @brief Return the API version. - virtual int ApiVersion() = 0; - - // @brief Initializes a new environment on the current thread. - // Currently, at most one environment may be created in a process. - virtual ISourcePawnEnvironment *NewEnvironment() = 0; - - // @brief Returns the environment for the calling thread. - virtual ISourcePawnEnvironment *CurrentEnvironment() = 0; - }; - - // @brief A function named "GetSourcePawnFactory" is exported from the - // SourcePawn DLL, conforming to the following signature: - typedef ISourcePawnFactory *(*GetSourcePawnFactoryFn)(int apiVersion); - - // @brief A helper class for handling exceptions. - // - // ExceptionHandlers can be used to detect, catch, and re-throw VM errors - // within C++ code. - // - // When throwing errors, SourcePawn creates an exception object. The - // exception object is global state. As long as an exception is present, - // all scripted code should immediately abort and return to their callers, - // all native code should exit, all code should propagate any error states - // until the exception is handled. - // - // In some cases, an error code is not available. For example, if a native - // detects an exception, it does not have an error status to propagate. It - // should simply return instead. The return value will be ignored; the VM - // knows to abort the script. - class ExceptionHandler - { - friend class sp::Environment; - - public: - ExceptionHandler(ISourcePawnEngine2 *api) - : env_(api->Environment()), - catch_(true) - { - env_->EnterExceptionHandlingScope(this); - } - ExceptionHandler(IPluginContext *ctx) - : env_(ctx->APIv2()->Environment()), - catch_(true) - { - env_->EnterExceptionHandlingScope(this); - } - ~ExceptionHandler() - { - env_->LeaveExceptionHandlingScope(this); - } - - virtual uint32_t ApiVersion() const { - return SOURCEPAWN_API_VERSION; - } - - // Propagates the exception instead of catching it. After calling this, - // no more SourcePawn code should be executed until the exception is - // handled. Callers should return immediately. - void Rethrow() { - assert(catch_ && HasException()); - catch_ = false; - } - - bool HasException() const { - return env_->HasPendingException(this); - } - - const char *Message() const { - return env_->GetPendingExceptionMessage(this); - } - - private: - // Don't allow heap construction. - ExceptionHandler(const ExceptionHandler &other); - void operator =(const ExceptionHandler &other); - void *operator new(size_t size); - void operator delete(void *, size_t); - - private: - ISourcePawnEnvironment *env_; - ExceptionHandler *next_; - - protected: - // If true, the exception will be swallowed. - bool catch_; - }; - - // @brief An implementation of ExceptionHandler that simply collects - // whether an exception was thrown. - class DetectExceptions : public ExceptionHandler - { - public: - DetectExceptions(ISourcePawnEngine2 *api) - : ExceptionHandler(api) - { - catch_ = false; - } - DetectExceptions(IPluginContext *ctx) - : ExceptionHandler(ctx) - { - catch_ = false; - } - }; -}; - -#endif //_INCLUDE_SOURCEPAWN_VM_API_H_ diff --git a/sourcepawn/include/sp_vm_base.h b/sourcepawn/include/sp_vm_base.h deleted file mode 100644 index dfcba8a8..00000000 --- a/sourcepawn/include/sp_vm_base.h +++ /dev/null @@ -1,51 +0,0 @@ -/** - * vim: set ts=4 : - * ============================================================================= - * SourcePawn - * Copyright (C) 2004-2008 AlliedModders LLC. All rights reserved. - * ============================================================================= - * - * This program is free software; you can redistribute it and/or modify it under - * the terms of the GNU General Public License, version 3.0, as published by the - * Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS - * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more - * details. - * - * You should have received a copy of the GNU General Public License along with - * this program. If not, see . - * - * As a special exception, AlliedModders LLC gives you permission to link the - * code of this program (as well as its derivative works) to "Half-Life 2," the - * "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software - * by the Valve Corporation. You must obey the GNU General Public License in - * all respects for all other code used. Additionally, AlliedModders LLC grants - * this exception to all derivative works. AlliedModders LLC defines further - * exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007), - * or . - * - * Version: $Id$ - */ - -#ifndef _INCLUDE_SOURCEPAWN_VM_BASE_H_ -#define _INCLUDE_SOURCEPAWN_VM_BASE_H_ - -/** - * @file sp_vm_base.h - * @brief Contains JIT export/linkage macros. - */ - -#include - -/* :TODO: rename this to sp_vm_linkage.h */ - -#if defined WIN32 -#define EXPORT_LINK extern "C" __declspec(dllexport) -#elif defined __GNUC__ -#define EXPORT_LINK extern "C" __attribute__((visibility("default"))) -#endif - -#endif //_INCLUDE_SOURCEPAWN_VM_BASE_H_ - diff --git a/sourcepawn/include/sp_vm_types.h b/sourcepawn/include/sp_vm_types.h deleted file mode 100644 index f637fcff..00000000 --- a/sourcepawn/include/sp_vm_types.h +++ /dev/null @@ -1,228 +0,0 @@ -/** - * vim: set ts=4 sw=4 tw=99 noet: - * ============================================================================= - * SourcePawn - * Copyright (C) 2004-2008 AlliedModders LLC. All rights reserved. - * ============================================================================= - * - * This program is free software; you can redistribute it and/or modify it under - * the terms of the GNU General Public License, version 3.0, as published by the - * Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS - * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more - * details. - * - * You should have received a copy of the GNU General Public License along with - * this program. If not, see . - * - * As a special exception, AlliedModders LLC gives you permission to link the - * code of this program (as well as its derivative works) to "Half-Life 2," the - * "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software - * by the Valve Corporation. You must obey the GNU General Public License in - * all respects for all other code used. Additionally, AlliedModders LLC grants - * this exception to all derivative works. AlliedModders LLC defines further - * exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007), - * or . - * - * Version: $Id$ - */ - -#ifndef _INCLUDE_SOURCEPAWN_VM_TYPES_H -#define _INCLUDE_SOURCEPAWN_VM_TYPES_H - -/** - * @file sp_vm_types.h - * @brief Contains all run-time SourcePawn structures. - */ -#include -#include - -typedef uint32_t ucell_t; /**< Unsigned 32bit integer */ -typedef int32_t cell_t; /**< Basic 32bit signed integer type for plugins */ -typedef uint32_t funcid_t; /**< Function index code */ - -#include "sp_typeutil.h" - -#define SP_MAX_EXEC_PARAMS 32 /**< Maximum number of parameters in a function */ - -#define SP_JITCONF_DEBUG "debug" /**< Configuration option for debugging. */ -#define SP_JITCONF_PROFILE "profile" /**< Configuration option for profiling. */ - -#define SP_PROF_NATIVES (1<<0) /**< Profile natives. */ -#define SP_PROF_CALLBACKS (1<<1) /**< Profile callbacks. */ -#define SP_PROF_FUNCTIONS (1<<2) /**< Profile functions. */ - -/** - * @brief Error codes for SourcePawn routines. - */ -#define SP_ERROR_NONE 0 /**< No error occurred */ -#define SP_ERROR_FILE_FORMAT 1 /**< File format unrecognized */ -#define SP_ERROR_DECOMPRESSOR 2 /**< A decompressor was not found */ -#define SP_ERROR_HEAPLOW 3 /**< Not enough space left on the heap */ -#define SP_ERROR_PARAM 4 /**< Invalid parameter or parameter type */ -#define SP_ERROR_INVALID_ADDRESS 5 /**< A memory address was not valid */ -#define SP_ERROR_NOT_FOUND 6 /**< The object in question was not found */ -#define SP_ERROR_INDEX 7 /**< Invalid index parameter */ -#define SP_ERROR_STACKLOW 8 /**< Not enough space left on the stack */ -#define SP_ERROR_NOTDEBUGGING 9 /**< Debug mode was not on or debug section not found */ -#define SP_ERROR_INVALID_INSTRUCTION 10 /**< Invalid instruction was encountered */ -#define SP_ERROR_MEMACCESS 11 /**< Invalid memory access */ -#define SP_ERROR_STACKMIN 12 /**< Stack went beyond its minimum value */ -#define SP_ERROR_HEAPMIN 13 /**< Heap went beyond its minimum value */ -#define SP_ERROR_DIVIDE_BY_ZERO 14 /**< Division by zero */ -#define SP_ERROR_ARRAY_BOUNDS 15 /**< Array index is out of bounds */ -#define SP_ERROR_INSTRUCTION_PARAM 16 /**< Instruction had an invalid parameter */ -#define SP_ERROR_STACKLEAK 17 /**< A native leaked an item on the stack */ -#define SP_ERROR_HEAPLEAK 18 /**< A native leaked an item on the heap */ -#define SP_ERROR_ARRAY_TOO_BIG 19 /**< A dynamic array is too big */ -#define SP_ERROR_TRACKER_BOUNDS 20 /**< Tracker stack is out of bounds */ -#define SP_ERROR_INVALID_NATIVE 21 /**< Native was pending or invalid */ -#define SP_ERROR_PARAMS_MAX 22 /**< Maximum number of parameters reached */ -#define SP_ERROR_NATIVE 23 /**< Error originates from a native */ -#define SP_ERROR_NOT_RUNNABLE 24 /**< Function or plugin is not runnable */ -#define SP_ERROR_ABORTED 25 /**< Function call was aborted */ -#define SP_ERROR_CODE_TOO_OLD 26 /**< Code is too old for this VM */ -#define SP_ERROR_CODE_TOO_NEW 27 /**< Code is too new for this VM */ -#define SP_ERROR_OUT_OF_MEMORY 28 /**< Out of memory */ -#define SP_ERROR_INTEGER_OVERFLOW 29 /**< Integer overflow (-INT_MIN / -1) */ -#define SP_ERROR_TIMEOUT 30 /**< Timeout */ -#define SP_ERROR_USER 31 /**< Custom message */ -#define SP_ERROR_FATAL 32 /**< Custom fatal message */ -#define SP_MAX_ERROR_CODES 33 -//Hey you! Update the string table if you add to the end of me! */ - -/********************************************** - *** The following structures are reference structures. - *** They are not essential to the API, but are used - *** to hold the back end database format of the plugin - *** binary. - **********************************************/ - -namespace SourcePawn -{ - class IPluginContext; - class IVirtualMachine; - class IProfiler; -}; - -struct sp_context_s; - -/** - * @brief Native callback prototype, passed a context and a parameter stack (0=count, 1+=args). - * A cell must be returned. - */ -typedef cell_t (*SPVM_NATIVE_FUNC)(SourcePawn::IPluginContext *, const cell_t *); - -/** - * @brief Fake native callback prototype, passed a context, parameter stack, and private data. - * A cell must be returned. - */ -typedef cell_t (*SPVM_FAKENATIVE_FUNC)(SourcePawn::IPluginContext *, const cell_t *, void *); - -/********************************************** - *** The following structures are bound to the VM/JIT. - *** Changing them will result in necessary recompilation. - **********************************************/ - -/** - * @brief Offsets and names to a public function. - */ -typedef struct sp_public_s -{ - funcid_t funcid; /**< Encoded function id */ - uint32_t code_offs; /**< Relocated code offset */ - const char *name; /**< Name of function */ -} sp_public_t; - -/** - * @brief Offsets and names to public variables. - * - * The offset is relocated and the name by default points back to the sp_plugin_infotab_t structure. - */ -typedef struct sp_pubvar_s -{ - cell_t *offs; /**< Pointer to data */ - const char *name; /**< Name */ -} sp_pubvar_t; - -#define SP_NATIVE_UNBOUND (0) /**< Native is undefined */ -#define SP_NATIVE_BOUND (1) /**< Native is bound */ - -#define SP_NTVFLAG_OPTIONAL (1<<0) /**< Native is optional */ -#define SP_NTVFLAG_EPHEMERAL (1<<1) /**< Native can be unbound */ - -/** - * @brief Native lookup table, by default names point back to the sp_plugin_infotab_t structure. - */ -typedef struct sp_native_s -{ - SPVM_NATIVE_FUNC pfn; /**< Function pointer */ - const char * name; /**< Name of function */ - uint32_t status; /**< Status flags */ - uint32_t flags; /**< Native flags */ - void * user; /**< Host-specific data */ -} sp_native_t; - -/** - * @brief Used for setting natives from modules/host apps. - */ -typedef struct sp_nativeinfo_s -{ - const char *name; /**< Name of the native */ - SPVM_NATIVE_FUNC func; /**< Address of native implementation */ -} sp_nativeinfo_t; - -/** - * @brief Run-time debug file table - */ -typedef struct sp_debug_file_s -{ - uint32_t addr; /**< Address into code */ - const char * name; /**< Name of file */ -} sp_debug_file_t; - -/** - * @brief Contains run-time debug line table. - */ -typedef struct sp_debug_line_s -{ - uint32_t addr; /**< Address into code */ - uint32_t line; /**< Line number */ -} sp_debug_line_t; - -// Occurs after an fdbg_symbol entry, for each dimension. -typedef struct sp_debug_arraydim_s -{ - int16_t tagid; /**< Tag id */ - uint32_t size; /**< Size of dimension */ -} sp_debug_arraydim_t; - -// Same as from . -typedef struct sp_debug_symbol_raw_s -{ - int32_t addr; /**< Address rel to DAT or stack frame */ - int16_t tagid; /**< Tag id */ - uint32_t codestart; /**< Start scope validity in code */ - uint32_t codeend; /**< End scope validity in code */ - uint8_t ident; /**< Variable type */ - uint8_t vclass; /**< Scope class (local vs global) */ - uint16_t dimcount; /**< Dimension count (for arrays) */ - uint32_t name; /**< Offset into debug nametable */ -} sp_debug_symbol_raw_t; - -/** - * @brief The majority of this struct is already located in the parent - * block. Thus, only the relocated portions are required. - */ -typedef struct sp_debug_symbol_s -{ - uint32_t codestart; /**< Relocated code address */ - uint32_t codeend; /**< Relocated code end address */ - const char * name; /**< Relocated name */ - sp_debug_arraydim_t *dims; /**< Relocated dimension struct, if any */ - sp_debug_symbol_raw_t *sym; /**< Pointer to original symbol */ -} sp_debug_symbol_t; - -#endif //_INCLUDE_SOURCEPAWN_VM_TYPES_H diff --git a/sourcepawn/third_party/zlib/adler32.c b/sourcepawn/third_party/zlib/adler32.c deleted file mode 100644 index f201d670..00000000 --- a/sourcepawn/third_party/zlib/adler32.c +++ /dev/null @@ -1,149 +0,0 @@ -/* adler32.c -- compute the Adler-32 checksum of a data stream - * Copyright (C) 1995-2004 Mark Adler - * For conditions of distribution and use, see copyright notice in zlib.h - */ - -/* @(#) $Id$ */ - -#define ZLIB_INTERNAL -#include "zlib.h" - -#define BASE 65521UL /* largest prime smaller than 65536 */ -#define NMAX 5552 -/* NMAX is the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1 */ - -#define DO1(buf,i) {adler += (buf)[i]; sum2 += adler;} -#define DO2(buf,i) DO1(buf,i); DO1(buf,i+1); -#define DO4(buf,i) DO2(buf,i); DO2(buf,i+2); -#define DO8(buf,i) DO4(buf,i); DO4(buf,i+4); -#define DO16(buf) DO8(buf,0); DO8(buf,8); - -/* use NO_DIVIDE if your processor does not do division in hardware */ -#ifdef NO_DIVIDE -# define MOD(a) \ - do { \ - if (a >= (BASE << 16)) a -= (BASE << 16); \ - if (a >= (BASE << 15)) a -= (BASE << 15); \ - if (a >= (BASE << 14)) a -= (BASE << 14); \ - if (a >= (BASE << 13)) a -= (BASE << 13); \ - if (a >= (BASE << 12)) a -= (BASE << 12); \ - if (a >= (BASE << 11)) a -= (BASE << 11); \ - if (a >= (BASE << 10)) a -= (BASE << 10); \ - if (a >= (BASE << 9)) a -= (BASE << 9); \ - if (a >= (BASE << 8)) a -= (BASE << 8); \ - if (a >= (BASE << 7)) a -= (BASE << 7); \ - if (a >= (BASE << 6)) a -= (BASE << 6); \ - if (a >= (BASE << 5)) a -= (BASE << 5); \ - if (a >= (BASE << 4)) a -= (BASE << 4); \ - if (a >= (BASE << 3)) a -= (BASE << 3); \ - if (a >= (BASE << 2)) a -= (BASE << 2); \ - if (a >= (BASE << 1)) a -= (BASE << 1); \ - if (a >= BASE) a -= BASE; \ - } while (0) -# define MOD4(a) \ - do { \ - if (a >= (BASE << 4)) a -= (BASE << 4); \ - if (a >= (BASE << 3)) a -= (BASE << 3); \ - if (a >= (BASE << 2)) a -= (BASE << 2); \ - if (a >= (BASE << 1)) a -= (BASE << 1); \ - if (a >= BASE) a -= BASE; \ - } while (0) -#else -# define MOD(a) a %= BASE -# define MOD4(a) a %= BASE -#endif - -/* ========================================================================= */ -uLong ZEXPORT adler32(adler, buf, len) - uLong adler; - const Bytef *buf; - uInt len; -{ - unsigned long sum2; - unsigned n; - - /* split Adler-32 into component sums */ - sum2 = (adler >> 16) & 0xffff; - adler &= 0xffff; - - /* in case user likes doing a byte at a time, keep it fast */ - if (len == 1) { - adler += buf[0]; - if (adler >= BASE) - adler -= BASE; - sum2 += adler; - if (sum2 >= BASE) - sum2 -= BASE; - return adler | (sum2 << 16); - } - - /* initial Adler-32 value (deferred check for len == 1 speed) */ - if (buf == Z_NULL) - return 1L; - - /* in case short lengths are provided, keep it somewhat fast */ - if (len < 16) { - while (len--) { - adler += *buf++; - sum2 += adler; - } - if (adler >= BASE) - adler -= BASE; - MOD4(sum2); /* only added so many BASE's */ - return adler | (sum2 << 16); - } - - /* do length NMAX blocks -- requires just one modulo operation */ - while (len >= NMAX) { - len -= NMAX; - n = NMAX / 16; /* NMAX is divisible by 16 */ - do { - DO16(buf); /* 16 sums unrolled */ - buf += 16; - } while (--n); - MOD(adler); - MOD(sum2); - } - - /* do remaining bytes (less than NMAX, still just one modulo) */ - if (len) { /* avoid modulos if none remaining */ - while (len >= 16) { - len -= 16; - DO16(buf); - buf += 16; - } - while (len--) { - adler += *buf++; - sum2 += adler; - } - MOD(adler); - MOD(sum2); - } - - /* return recombined sums */ - return adler | (sum2 << 16); -} - -/* ========================================================================= */ -uLong ZEXPORT adler32_combine(adler1, adler2, len2) - uLong adler1; - uLong adler2; - z_off_t len2; -{ - unsigned long sum1; - unsigned long sum2; - unsigned rem; - - /* the derivation of this formula is left as an exercise for the reader */ - rem = (unsigned)(len2 % BASE); - sum1 = adler1 & 0xffff; - sum2 = rem * sum1; - MOD(sum2); - sum1 += (adler2 & 0xffff) + BASE - 1; - sum2 += ((adler1 >> 16) & 0xffff) + ((adler2 >> 16) & 0xffff) + BASE - rem; - if (sum1 > BASE) sum1 -= BASE; - if (sum1 > BASE) sum1 -= BASE; - if (sum2 > (BASE << 1)) sum2 -= (BASE << 1); - if (sum2 > BASE) sum2 -= BASE; - return sum1 | (sum2 << 16); -} diff --git a/sourcepawn/third_party/zlib/compress.c b/sourcepawn/third_party/zlib/compress.c deleted file mode 100644 index d37e84f5..00000000 --- a/sourcepawn/third_party/zlib/compress.c +++ /dev/null @@ -1,79 +0,0 @@ -/* compress.c -- compress a memory buffer - * Copyright (C) 1995-2003 Jean-loup Gailly. - * For conditions of distribution and use, see copyright notice in zlib.h - */ - -/* @(#) $Id$ */ - -#define ZLIB_INTERNAL -#include "zlib.h" - -/* =========================================================================== - Compresses the source buffer into the destination buffer. The level - parameter has the same meaning as in deflateInit. sourceLen is the byte - length of the source buffer. Upon entry, destLen is the total size of the - destination buffer, which must be at least 0.1% larger than sourceLen plus - 12 bytes. Upon exit, destLen is the actual size of the compressed buffer. - - compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough - memory, Z_BUF_ERROR if there was not enough room in the output buffer, - Z_STREAM_ERROR if the level parameter is invalid. -*/ -int ZEXPORT compress2 (dest, destLen, source, sourceLen, level) - Bytef *dest; - uLongf *destLen; - const Bytef *source; - uLong sourceLen; - int level; -{ - z_stream stream; - int err; - - stream.next_in = (Bytef*)source; - stream.avail_in = (uInt)sourceLen; -#ifdef MAXSEG_64K - /* Check for source > 64K on 16-bit machine: */ - if ((uLong)stream.avail_in != sourceLen) return Z_BUF_ERROR; -#endif - stream.next_out = dest; - stream.avail_out = (uInt)*destLen; - if ((uLong)stream.avail_out != *destLen) return Z_BUF_ERROR; - - stream.zalloc = (alloc_func)0; - stream.zfree = (free_func)0; - stream.opaque = (voidpf)0; - - err = deflateInit(&stream, level); - if (err != Z_OK) return err; - - err = deflate(&stream, Z_FINISH); - if (err != Z_STREAM_END) { - deflateEnd(&stream); - return err == Z_OK ? Z_BUF_ERROR : err; - } - *destLen = stream.total_out; - - err = deflateEnd(&stream); - return err; -} - -/* =========================================================================== - */ -int ZEXPORT compress (dest, destLen, source, sourceLen) - Bytef *dest; - uLongf *destLen; - const Bytef *source; - uLong sourceLen; -{ - return compress2(dest, destLen, source, sourceLen, Z_DEFAULT_COMPRESSION); -} - -/* =========================================================================== - If the default memLevel or windowBits for deflateInit() is changed, then - this function needs to be updated. - */ -uLong ZEXPORT compressBound (sourceLen) - uLong sourceLen; -{ - return sourceLen + (sourceLen >> 12) + (sourceLen >> 14) + 11; -} diff --git a/sourcepawn/third_party/zlib/crc32.c b/sourcepawn/third_party/zlib/crc32.c deleted file mode 100644 index 5e8c44be..00000000 --- a/sourcepawn/third_party/zlib/crc32.c +++ /dev/null @@ -1,424 +0,0 @@ -/* crc32.c -- compute the CRC-32 of a data stream - * Copyright (C) 1995-2005 Mark Adler - * For conditions of distribution and use, see copyright notice in zlib.h - * - * Thanks to Rodney Brown for his contribution of faster - * CRC methods: exclusive-oring 32 bits of data at a time, and pre-computing - * tables for updating the shift register in one step with three exclusive-ors - * instead of four steps with four exclusive-ors. This results in about a - * factor of two increase in speed on a Power PC G4 (PPC7455) using gcc -O3. - */ - -/* @(#) $Id$ */ - -/* - Note on the use of DYNAMIC_CRC_TABLE: there is no mutex or semaphore - protection on the static variables used to control the first-use generation - of the crc tables. Therefore, if you #define DYNAMIC_CRC_TABLE, you should - first call get_crc_table() to initialize the tables before allowing more than - one thread to use crc32(). - */ - -#include -#ifdef MAKECRCH -# include -# ifndef DYNAMIC_CRC_TABLE -# define DYNAMIC_CRC_TABLE -# endif /* !DYNAMIC_CRC_TABLE */ -#endif /* MAKECRCH */ - -#include "zutil.h" /* for STDC and FAR definitions */ - -#define local static - -/* Find a four-byte integer type for crc32_little() and crc32_big(). */ -#ifndef NOBYFOUR -# ifdef STDC /* need ANSI C limits.h to determine sizes */ -# include -# define BYFOUR -# if (UINT_MAX == 0xffffffffUL) - typedef unsigned int u4; -# else -# if (ULONG_MAX == 0xffffffffUL) - typedef unsigned long u4; -# else -# if (USHRT_MAX == 0xffffffffUL) - typedef unsigned short u4; -# else -# undef BYFOUR /* can't find a four-byte integer type! */ -# endif -# endif -# endif -# endif /* STDC */ -#endif /* !NOBYFOUR */ - -/* Definitions for doing the crc four data bytes at a time. */ -#ifdef BYFOUR -# define REV(w) (((w)>>24)+(((w)>>8)&0xff00)+ \ - (((w)&0xff00)<<8)+(((w)&0xff)<<24)) - local unsigned long crc32_little OF((unsigned long, - const unsigned char FAR *, unsigned)); - local unsigned long crc32_big OF((unsigned long, - const unsigned char FAR *, unsigned)); -# define TBLS 8 -#else -# define TBLS 1 -#endif /* BYFOUR */ - -/* Local functions for crc concatenation */ -local unsigned long gf2_matrix_times OF((unsigned long *mat, - unsigned long vec)); -local void gf2_matrix_square OF((unsigned long *square, unsigned long *mat)); - -#ifdef DYNAMIC_CRC_TABLE - -local volatile int crc_table_empty = 1; -local unsigned long FAR crc_table[TBLS][256]; -local void make_crc_table OF((void)); -#ifdef MAKECRCH - local void write_table OF((FILE *, const unsigned long FAR *)); -#endif /* MAKECRCH */ -/* - Generate tables for a byte-wise 32-bit CRC calculation on the polynomial: - x^32+x^26+x^23+x^22+x^16+x^12+x^11+x^10+x^8+x^7+x^5+x^4+x^2+x+1. - - Polynomials over GF(2) are represented in binary, one bit per coefficient, - with the lowest powers in the most significant bit. Then adding polynomials - is just exclusive-or, and multiplying a polynomial by x is a right shift by - one. If we call the above polynomial p, and represent a byte as the - polynomial q, also with the lowest power in the most significant bit (so the - byte 0xb1 is the polynomial x^7+x^3+x+1), then the CRC is (q*x^32) mod p, - where a mod b means the remainder after dividing a by b. - - This calculation is done using the shift-register method of multiplying and - taking the remainder. The register is initialized to zero, and for each - incoming bit, x^32 is added mod p to the register if the bit is a one (where - x^32 mod p is p+x^32 = x^26+...+1), and the register is multiplied mod p by - x (which is shifting right by one and adding x^32 mod p if the bit shifted - out is a one). We start with the highest power (least significant bit) of - q and repeat for all eight bits of q. - - The first table is simply the CRC of all possible eight bit values. This is - all the information needed to generate CRCs on data a byte at a time for all - combinations of CRC register values and incoming bytes. The remaining tables - allow for word-at-a-time CRC calculation for both big-endian and little- - endian machines, where a word is four bytes. -*/ -local void make_crc_table() -{ - unsigned long c; - int n, k; - unsigned long poly; /* polynomial exclusive-or pattern */ - /* terms of polynomial defining this crc (except x^32): */ - static volatile int first = 1; /* flag to limit concurrent making */ - static const unsigned char p[] = {0,1,2,4,5,7,8,10,11,12,16,22,23,26}; - - /* See if another task is already doing this (not thread-safe, but better - than nothing -- significantly reduces duration of vulnerability in - case the advice about DYNAMIC_CRC_TABLE is ignored) */ - if (first) { - first = 0; - - /* make exclusive-or pattern from polynomial (0xedb88320UL) */ - poly = 0UL; - for (n = 0; n < sizeof(p)/sizeof(unsigned char); n++) - poly |= 1UL << (31 - p[n]); - - /* generate a crc for every 8-bit value */ - for (n = 0; n < 256; n++) { - c = (unsigned long)n; - for (k = 0; k < 8; k++) - c = c & 1 ? poly ^ (c >> 1) : c >> 1; - crc_table[0][n] = c; - } - -#ifdef BYFOUR - /* generate crc for each value followed by one, two, and three zeros, - and then the byte reversal of those as well as the first table */ - for (n = 0; n < 256; n++) { - c = crc_table[0][n]; - crc_table[4][n] = REV(c); - for (k = 1; k < 4; k++) { - c = crc_table[0][c & 0xff] ^ (c >> 8); - crc_table[k][n] = c; - crc_table[k + 4][n] = REV(c); - } - } -#endif /* BYFOUR */ - - crc_table_empty = 0; - } - else { /* not first */ - /* wait for the other guy to finish (not efficient, but rare) */ - while (crc_table_empty) - ; - } - -#ifdef MAKECRCH - /* write out CRC tables to crc32.h */ - { - FILE *out; - - out = fopen("crc32.h", "w"); - if (out == NULL) return; - fprintf(out, "/* crc32.h -- tables for rapid CRC calculation\n"); - fprintf(out, " * Generated automatically by crc32.c\n */\n\n"); - fprintf(out, "local const unsigned long FAR "); - fprintf(out, "crc_table[TBLS][256] =\n{\n {\n"); - write_table(out, crc_table[0]); -# ifdef BYFOUR - fprintf(out, "#ifdef BYFOUR\n"); - for (k = 1; k < 8; k++) { - fprintf(out, " },\n {\n"); - write_table(out, crc_table[k]); - } - fprintf(out, "#endif\n"); -# endif /* BYFOUR */ - fprintf(out, " }\n};\n"); - fclose(out); - } -#endif /* MAKECRCH */ -} - -#ifdef MAKECRCH -local void write_table(out, table) - FILE *out; - const unsigned long FAR *table; -{ - int n; - - for (n = 0; n < 256; n++) - fprintf(out, "%s0x%08lxUL%s", n % 5 ? "" : " ", table[n], - n == 255 ? "\n" : (n % 5 == 4 ? ",\n" : ", ")); -} -#endif /* MAKECRCH */ - -#else /* !DYNAMIC_CRC_TABLE */ -/* ======================================================================== - * Tables of CRC-32s of all single-byte values, made by make_crc_table(). - */ -#include "crc32.h" -#endif /* DYNAMIC_CRC_TABLE */ - -/* ========================================================================= - * This function can be used by asm versions of crc32() - */ -const unsigned long FAR * ZEXPORT get_crc_table() -{ -#ifdef DYNAMIC_CRC_TABLE - if (crc_table_empty) - make_crc_table(); -#endif /* DYNAMIC_CRC_TABLE */ - return (const unsigned long FAR *)crc_table; -} - -/* ========================================================================= */ -#define DO1 crc = crc_table[0][((int)crc ^ (*buf++)) & 0xff] ^ (crc >> 8) -#define DO8 DO1; DO1; DO1; DO1; DO1; DO1; DO1; DO1 - -/* ========================================================================= */ -unsigned long ZEXPORT crc32(crc, buf, len) - unsigned long crc; - const unsigned char FAR *buf; - unsigned len; -{ - if (buf == Z_NULL) return 0UL; - -#ifdef DYNAMIC_CRC_TABLE - if (crc_table_empty) - make_crc_table(); -#endif /* DYNAMIC_CRC_TABLE */ - -#ifdef BYFOUR - if (sizeof(void *) == sizeof(ptrdiff_t)) { - u4 endian; - - endian = 1; - if (*((unsigned char *)(&endian))) - return crc32_little(crc, buf, len); - else - return crc32_big(crc, buf, len); - } -#endif /* BYFOUR */ - crc = crc ^ 0xffffffffUL; - while (len >= 8) { - DO8; - len -= 8; - } - if (len) do { - DO1; - } while (--len); - return crc ^ 0xffffffffUL; -} - -#ifdef BYFOUR - -/* ========================================================================= */ -#define DOLIT4 c ^= *buf4++; \ - c = crc_table[3][c & 0xff] ^ crc_table[2][(c >> 8) & 0xff] ^ \ - crc_table[1][(c >> 16) & 0xff] ^ crc_table[0][c >> 24] -#define DOLIT32 DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4 - -/* ========================================================================= */ -local unsigned long crc32_little(crc, buf, len) - unsigned long crc; - const unsigned char FAR *buf; - unsigned len; -{ - register u4 c; - register const u4 FAR *buf4; - - c = (u4)crc; - c = ~c; - while (len && ((ptrdiff_t)buf & 3)) { - c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8); - len--; - } - - buf4 = (const u4 FAR *)(const void FAR *)buf; - while (len >= 32) { - DOLIT32; - len -= 32; - } - while (len >= 4) { - DOLIT4; - len -= 4; - } - buf = (const unsigned char FAR *)buf4; - - if (len) do { - c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8); - } while (--len); - c = ~c; - return (unsigned long)c; -} - -/* ========================================================================= */ -#define DOBIG4 c ^= *++buf4; \ - c = crc_table[4][c & 0xff] ^ crc_table[5][(c >> 8) & 0xff] ^ \ - crc_table[6][(c >> 16) & 0xff] ^ crc_table[7][c >> 24] -#define DOBIG32 DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4 - -/* ========================================================================= */ -local unsigned long crc32_big(crc, buf, len) - unsigned long crc; - const unsigned char FAR *buf; - unsigned len; -{ - register u4 c; - register const u4 FAR *buf4; - - c = REV((u4)crc); - c = ~c; - while (len && ((ptrdiff_t)buf & 3)) { - c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8); - len--; - } - - buf4 = (const u4 FAR *)(const void FAR *)buf; - buf4--; - while (len >= 32) { - DOBIG32; - len -= 32; - } - while (len >= 4) { - DOBIG4; - len -= 4; - } - buf4++; - buf = (const unsigned char FAR *)buf4; - - if (len) do { - c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8); - } while (--len); - c = ~c; - return (unsigned long)(REV(c)); -} - -#endif /* BYFOUR */ - -#define GF2_DIM 32 /* dimension of GF(2) vectors (length of CRC) */ - -/* ========================================================================= */ -local unsigned long gf2_matrix_times(mat, vec) - unsigned long *mat; - unsigned long vec; -{ - unsigned long sum; - - sum = 0; - while (vec) { - if (vec & 1) - sum ^= *mat; - vec >>= 1; - mat++; - } - return sum; -} - -/* ========================================================================= */ -local void gf2_matrix_square(square, mat) - unsigned long *square; - unsigned long *mat; -{ - int n; - - for (n = 0; n < GF2_DIM; n++) - square[n] = gf2_matrix_times(mat, mat[n]); -} - -/* ========================================================================= */ -uLong ZEXPORT crc32_combine(crc1, crc2, len2) - uLong crc1; - uLong crc2; - z_off_t len2; -{ - int n; - unsigned long row; - unsigned long even[GF2_DIM]; /* even-power-of-two zeros operator */ - unsigned long odd[GF2_DIM]; /* odd-power-of-two zeros operator */ - - /* degenerate case */ - if (len2 == 0) - return crc1; - - /* put operator for one zero bit in odd */ - odd[0] = 0xedb88320L; /* CRC-32 polynomial */ - row = 1; - for (n = 1; n < GF2_DIM; n++) { - odd[n] = row; - row <<= 1; - } - - /* put operator for two zero bits in even */ - gf2_matrix_square(even, odd); - - /* put operator for four zero bits in odd */ - gf2_matrix_square(odd, even); - - /* apply len2 zeros to crc1 (first square will put the operator for one - zero byte, eight zero bits, in even) */ - do { - /* apply zeros operator for this bit of len2 */ - gf2_matrix_square(even, odd); - if (len2 & 1) - crc1 = gf2_matrix_times(even, crc1); - len2 >>= 1; - - /* if no more bits set, then done */ - if (len2 == 0) - break; - - /* another iteration of the loop with odd and even swapped */ - gf2_matrix_square(odd, even); - if (len2 & 1) - crc1 = gf2_matrix_times(odd, crc1); - len2 >>= 1; - - /* if no more bits set, then done */ - } while (len2 != 0); - - /* return combined crc */ - crc1 ^= crc2; - return crc1; -} diff --git a/sourcepawn/third_party/zlib/crc32.h b/sourcepawn/third_party/zlib/crc32.h deleted file mode 100644 index 5de49bc9..00000000 --- a/sourcepawn/third_party/zlib/crc32.h +++ /dev/null @@ -1,441 +0,0 @@ -/* crc32.h -- tables for rapid CRC calculation - * Generated automatically by crc32.c - */ - -local const unsigned long FAR crc_table[TBLS][256] = -{ - { - 0x00000000UL, 0x77073096UL, 0xee0e612cUL, 0x990951baUL, 0x076dc419UL, - 0x706af48fUL, 0xe963a535UL, 0x9e6495a3UL, 0x0edb8832UL, 0x79dcb8a4UL, - 0xe0d5e91eUL, 0x97d2d988UL, 0x09b64c2bUL, 0x7eb17cbdUL, 0xe7b82d07UL, - 0x90bf1d91UL, 0x1db71064UL, 0x6ab020f2UL, 0xf3b97148UL, 0x84be41deUL, - 0x1adad47dUL, 0x6ddde4ebUL, 0xf4d4b551UL, 0x83d385c7UL, 0x136c9856UL, - 0x646ba8c0UL, 0xfd62f97aUL, 0x8a65c9ecUL, 0x14015c4fUL, 0x63066cd9UL, - 0xfa0f3d63UL, 0x8d080df5UL, 0x3b6e20c8UL, 0x4c69105eUL, 0xd56041e4UL, - 0xa2677172UL, 0x3c03e4d1UL, 0x4b04d447UL, 0xd20d85fdUL, 0xa50ab56bUL, - 0x35b5a8faUL, 0x42b2986cUL, 0xdbbbc9d6UL, 0xacbcf940UL, 0x32d86ce3UL, - 0x45df5c75UL, 0xdcd60dcfUL, 0xabd13d59UL, 0x26d930acUL, 0x51de003aUL, - 0xc8d75180UL, 0xbfd06116UL, 0x21b4f4b5UL, 0x56b3c423UL, 0xcfba9599UL, - 0xb8bda50fUL, 0x2802b89eUL, 0x5f058808UL, 0xc60cd9b2UL, 0xb10be924UL, - 0x2f6f7c87UL, 0x58684c11UL, 0xc1611dabUL, 0xb6662d3dUL, 0x76dc4190UL, - 0x01db7106UL, 0x98d220bcUL, 0xefd5102aUL, 0x71b18589UL, 0x06b6b51fUL, - 0x9fbfe4a5UL, 0xe8b8d433UL, 0x7807c9a2UL, 0x0f00f934UL, 0x9609a88eUL, - 0xe10e9818UL, 0x7f6a0dbbUL, 0x086d3d2dUL, 0x91646c97UL, 0xe6635c01UL, - 0x6b6b51f4UL, 0x1c6c6162UL, 0x856530d8UL, 0xf262004eUL, 0x6c0695edUL, - 0x1b01a57bUL, 0x8208f4c1UL, 0xf50fc457UL, 0x65b0d9c6UL, 0x12b7e950UL, - 0x8bbeb8eaUL, 0xfcb9887cUL, 0x62dd1ddfUL, 0x15da2d49UL, 0x8cd37cf3UL, - 0xfbd44c65UL, 0x4db26158UL, 0x3ab551ceUL, 0xa3bc0074UL, 0xd4bb30e2UL, - 0x4adfa541UL, 0x3dd895d7UL, 0xa4d1c46dUL, 0xd3d6f4fbUL, 0x4369e96aUL, - 0x346ed9fcUL, 0xad678846UL, 0xda60b8d0UL, 0x44042d73UL, 0x33031de5UL, - 0xaa0a4c5fUL, 0xdd0d7cc9UL, 0x5005713cUL, 0x270241aaUL, 0xbe0b1010UL, - 0xc90c2086UL, 0x5768b525UL, 0x206f85b3UL, 0xb966d409UL, 0xce61e49fUL, - 0x5edef90eUL, 0x29d9c998UL, 0xb0d09822UL, 0xc7d7a8b4UL, 0x59b33d17UL, - 0x2eb40d81UL, 0xb7bd5c3bUL, 0xc0ba6cadUL, 0xedb88320UL, 0x9abfb3b6UL, - 0x03b6e20cUL, 0x74b1d29aUL, 0xead54739UL, 0x9dd277afUL, 0x04db2615UL, - 0x73dc1683UL, 0xe3630b12UL, 0x94643b84UL, 0x0d6d6a3eUL, 0x7a6a5aa8UL, - 0xe40ecf0bUL, 0x9309ff9dUL, 0x0a00ae27UL, 0x7d079eb1UL, 0xf00f9344UL, - 0x8708a3d2UL, 0x1e01f268UL, 0x6906c2feUL, 0xf762575dUL, 0x806567cbUL, - 0x196c3671UL, 0x6e6b06e7UL, 0xfed41b76UL, 0x89d32be0UL, 0x10da7a5aUL, - 0x67dd4accUL, 0xf9b9df6fUL, 0x8ebeeff9UL, 0x17b7be43UL, 0x60b08ed5UL, - 0xd6d6a3e8UL, 0xa1d1937eUL, 0x38d8c2c4UL, 0x4fdff252UL, 0xd1bb67f1UL, - 0xa6bc5767UL, 0x3fb506ddUL, 0x48b2364bUL, 0xd80d2bdaUL, 0xaf0a1b4cUL, - 0x36034af6UL, 0x41047a60UL, 0xdf60efc3UL, 0xa867df55UL, 0x316e8eefUL, - 0x4669be79UL, 0xcb61b38cUL, 0xbc66831aUL, 0x256fd2a0UL, 0x5268e236UL, - 0xcc0c7795UL, 0xbb0b4703UL, 0x220216b9UL, 0x5505262fUL, 0xc5ba3bbeUL, - 0xb2bd0b28UL, 0x2bb45a92UL, 0x5cb36a04UL, 0xc2d7ffa7UL, 0xb5d0cf31UL, - 0x2cd99e8bUL, 0x5bdeae1dUL, 0x9b64c2b0UL, 0xec63f226UL, 0x756aa39cUL, - 0x026d930aUL, 0x9c0906a9UL, 0xeb0e363fUL, 0x72076785UL, 0x05005713UL, - 0x95bf4a82UL, 0xe2b87a14UL, 0x7bb12baeUL, 0x0cb61b38UL, 0x92d28e9bUL, - 0xe5d5be0dUL, 0x7cdcefb7UL, 0x0bdbdf21UL, 0x86d3d2d4UL, 0xf1d4e242UL, - 0x68ddb3f8UL, 0x1fda836eUL, 0x81be16cdUL, 0xf6b9265bUL, 0x6fb077e1UL, - 0x18b74777UL, 0x88085ae6UL, 0xff0f6a70UL, 0x66063bcaUL, 0x11010b5cUL, - 0x8f659effUL, 0xf862ae69UL, 0x616bffd3UL, 0x166ccf45UL, 0xa00ae278UL, - 0xd70dd2eeUL, 0x4e048354UL, 0x3903b3c2UL, 0xa7672661UL, 0xd06016f7UL, - 0x4969474dUL, 0x3e6e77dbUL, 0xaed16a4aUL, 0xd9d65adcUL, 0x40df0b66UL, - 0x37d83bf0UL, 0xa9bcae53UL, 0xdebb9ec5UL, 0x47b2cf7fUL, 0x30b5ffe9UL, - 0xbdbdf21cUL, 0xcabac28aUL, 0x53b39330UL, 0x24b4a3a6UL, 0xbad03605UL, - 0xcdd70693UL, 0x54de5729UL, 0x23d967bfUL, 0xb3667a2eUL, 0xc4614ab8UL, - 0x5d681b02UL, 0x2a6f2b94UL, 0xb40bbe37UL, 0xc30c8ea1UL, 0x5a05df1bUL, - 0x2d02ef8dUL -#ifdef BYFOUR - }, - { - 0x00000000UL, 0x191b3141UL, 0x32366282UL, 0x2b2d53c3UL, 0x646cc504UL, - 0x7d77f445UL, 0x565aa786UL, 0x4f4196c7UL, 0xc8d98a08UL, 0xd1c2bb49UL, - 0xfaefe88aUL, 0xe3f4d9cbUL, 0xacb54f0cUL, 0xb5ae7e4dUL, 0x9e832d8eUL, - 0x87981ccfUL, 0x4ac21251UL, 0x53d92310UL, 0x78f470d3UL, 0x61ef4192UL, - 0x2eaed755UL, 0x37b5e614UL, 0x1c98b5d7UL, 0x05838496UL, 0x821b9859UL, - 0x9b00a918UL, 0xb02dfadbUL, 0xa936cb9aUL, 0xe6775d5dUL, 0xff6c6c1cUL, - 0xd4413fdfUL, 0xcd5a0e9eUL, 0x958424a2UL, 0x8c9f15e3UL, 0xa7b24620UL, - 0xbea97761UL, 0xf1e8e1a6UL, 0xe8f3d0e7UL, 0xc3de8324UL, 0xdac5b265UL, - 0x5d5daeaaUL, 0x44469febUL, 0x6f6bcc28UL, 0x7670fd69UL, 0x39316baeUL, - 0x202a5aefUL, 0x0b07092cUL, 0x121c386dUL, 0xdf4636f3UL, 0xc65d07b2UL, - 0xed705471UL, 0xf46b6530UL, 0xbb2af3f7UL, 0xa231c2b6UL, 0x891c9175UL, - 0x9007a034UL, 0x179fbcfbUL, 0x0e848dbaUL, 0x25a9de79UL, 0x3cb2ef38UL, - 0x73f379ffUL, 0x6ae848beUL, 0x41c51b7dUL, 0x58de2a3cUL, 0xf0794f05UL, - 0xe9627e44UL, 0xc24f2d87UL, 0xdb541cc6UL, 0x94158a01UL, 0x8d0ebb40UL, - 0xa623e883UL, 0xbf38d9c2UL, 0x38a0c50dUL, 0x21bbf44cUL, 0x0a96a78fUL, - 0x138d96ceUL, 0x5ccc0009UL, 0x45d73148UL, 0x6efa628bUL, 0x77e153caUL, - 0xbabb5d54UL, 0xa3a06c15UL, 0x888d3fd6UL, 0x91960e97UL, 0xded79850UL, - 0xc7cca911UL, 0xece1fad2UL, 0xf5facb93UL, 0x7262d75cUL, 0x6b79e61dUL, - 0x4054b5deUL, 0x594f849fUL, 0x160e1258UL, 0x0f152319UL, 0x243870daUL, - 0x3d23419bUL, 0x65fd6ba7UL, 0x7ce65ae6UL, 0x57cb0925UL, 0x4ed03864UL, - 0x0191aea3UL, 0x188a9fe2UL, 0x33a7cc21UL, 0x2abcfd60UL, 0xad24e1afUL, - 0xb43fd0eeUL, 0x9f12832dUL, 0x8609b26cUL, 0xc94824abUL, 0xd05315eaUL, - 0xfb7e4629UL, 0xe2657768UL, 0x2f3f79f6UL, 0x362448b7UL, 0x1d091b74UL, - 0x04122a35UL, 0x4b53bcf2UL, 0x52488db3UL, 0x7965de70UL, 0x607eef31UL, - 0xe7e6f3feUL, 0xfefdc2bfUL, 0xd5d0917cUL, 0xcccba03dUL, 0x838a36faUL, - 0x9a9107bbUL, 0xb1bc5478UL, 0xa8a76539UL, 0x3b83984bUL, 0x2298a90aUL, - 0x09b5fac9UL, 0x10aecb88UL, 0x5fef5d4fUL, 0x46f46c0eUL, 0x6dd93fcdUL, - 0x74c20e8cUL, 0xf35a1243UL, 0xea412302UL, 0xc16c70c1UL, 0xd8774180UL, - 0x9736d747UL, 0x8e2de606UL, 0xa500b5c5UL, 0xbc1b8484UL, 0x71418a1aUL, - 0x685abb5bUL, 0x4377e898UL, 0x5a6cd9d9UL, 0x152d4f1eUL, 0x0c367e5fUL, - 0x271b2d9cUL, 0x3e001cddUL, 0xb9980012UL, 0xa0833153UL, 0x8bae6290UL, - 0x92b553d1UL, 0xddf4c516UL, 0xc4eff457UL, 0xefc2a794UL, 0xf6d996d5UL, - 0xae07bce9UL, 0xb71c8da8UL, 0x9c31de6bUL, 0x852aef2aUL, 0xca6b79edUL, - 0xd37048acUL, 0xf85d1b6fUL, 0xe1462a2eUL, 0x66de36e1UL, 0x7fc507a0UL, - 0x54e85463UL, 0x4df36522UL, 0x02b2f3e5UL, 0x1ba9c2a4UL, 0x30849167UL, - 0x299fa026UL, 0xe4c5aeb8UL, 0xfdde9ff9UL, 0xd6f3cc3aUL, 0xcfe8fd7bUL, - 0x80a96bbcUL, 0x99b25afdUL, 0xb29f093eUL, 0xab84387fUL, 0x2c1c24b0UL, - 0x350715f1UL, 0x1e2a4632UL, 0x07317773UL, 0x4870e1b4UL, 0x516bd0f5UL, - 0x7a468336UL, 0x635db277UL, 0xcbfad74eUL, 0xd2e1e60fUL, 0xf9ccb5ccUL, - 0xe0d7848dUL, 0xaf96124aUL, 0xb68d230bUL, 0x9da070c8UL, 0x84bb4189UL, - 0x03235d46UL, 0x1a386c07UL, 0x31153fc4UL, 0x280e0e85UL, 0x674f9842UL, - 0x7e54a903UL, 0x5579fac0UL, 0x4c62cb81UL, 0x8138c51fUL, 0x9823f45eUL, - 0xb30ea79dUL, 0xaa1596dcUL, 0xe554001bUL, 0xfc4f315aUL, 0xd7626299UL, - 0xce7953d8UL, 0x49e14f17UL, 0x50fa7e56UL, 0x7bd72d95UL, 0x62cc1cd4UL, - 0x2d8d8a13UL, 0x3496bb52UL, 0x1fbbe891UL, 0x06a0d9d0UL, 0x5e7ef3ecUL, - 0x4765c2adUL, 0x6c48916eUL, 0x7553a02fUL, 0x3a1236e8UL, 0x230907a9UL, - 0x0824546aUL, 0x113f652bUL, 0x96a779e4UL, 0x8fbc48a5UL, 0xa4911b66UL, - 0xbd8a2a27UL, 0xf2cbbce0UL, 0xebd08da1UL, 0xc0fdde62UL, 0xd9e6ef23UL, - 0x14bce1bdUL, 0x0da7d0fcUL, 0x268a833fUL, 0x3f91b27eUL, 0x70d024b9UL, - 0x69cb15f8UL, 0x42e6463bUL, 0x5bfd777aUL, 0xdc656bb5UL, 0xc57e5af4UL, - 0xee530937UL, 0xf7483876UL, 0xb809aeb1UL, 0xa1129ff0UL, 0x8a3fcc33UL, - 0x9324fd72UL - }, - { - 0x00000000UL, 0x01c26a37UL, 0x0384d46eUL, 0x0246be59UL, 0x0709a8dcUL, - 0x06cbc2ebUL, 0x048d7cb2UL, 0x054f1685UL, 0x0e1351b8UL, 0x0fd13b8fUL, - 0x0d9785d6UL, 0x0c55efe1UL, 0x091af964UL, 0x08d89353UL, 0x0a9e2d0aUL, - 0x0b5c473dUL, 0x1c26a370UL, 0x1de4c947UL, 0x1fa2771eUL, 0x1e601d29UL, - 0x1b2f0bacUL, 0x1aed619bUL, 0x18abdfc2UL, 0x1969b5f5UL, 0x1235f2c8UL, - 0x13f798ffUL, 0x11b126a6UL, 0x10734c91UL, 0x153c5a14UL, 0x14fe3023UL, - 0x16b88e7aUL, 0x177ae44dUL, 0x384d46e0UL, 0x398f2cd7UL, 0x3bc9928eUL, - 0x3a0bf8b9UL, 0x3f44ee3cUL, 0x3e86840bUL, 0x3cc03a52UL, 0x3d025065UL, - 0x365e1758UL, 0x379c7d6fUL, 0x35dac336UL, 0x3418a901UL, 0x3157bf84UL, - 0x3095d5b3UL, 0x32d36beaUL, 0x331101ddUL, 0x246be590UL, 0x25a98fa7UL, - 0x27ef31feUL, 0x262d5bc9UL, 0x23624d4cUL, 0x22a0277bUL, 0x20e69922UL, - 0x2124f315UL, 0x2a78b428UL, 0x2bbade1fUL, 0x29fc6046UL, 0x283e0a71UL, - 0x2d711cf4UL, 0x2cb376c3UL, 0x2ef5c89aUL, 0x2f37a2adUL, 0x709a8dc0UL, - 0x7158e7f7UL, 0x731e59aeUL, 0x72dc3399UL, 0x7793251cUL, 0x76514f2bUL, - 0x7417f172UL, 0x75d59b45UL, 0x7e89dc78UL, 0x7f4bb64fUL, 0x7d0d0816UL, - 0x7ccf6221UL, 0x798074a4UL, 0x78421e93UL, 0x7a04a0caUL, 0x7bc6cafdUL, - 0x6cbc2eb0UL, 0x6d7e4487UL, 0x6f38fadeUL, 0x6efa90e9UL, 0x6bb5866cUL, - 0x6a77ec5bUL, 0x68315202UL, 0x69f33835UL, 0x62af7f08UL, 0x636d153fUL, - 0x612bab66UL, 0x60e9c151UL, 0x65a6d7d4UL, 0x6464bde3UL, 0x662203baUL, - 0x67e0698dUL, 0x48d7cb20UL, 0x4915a117UL, 0x4b531f4eUL, 0x4a917579UL, - 0x4fde63fcUL, 0x4e1c09cbUL, 0x4c5ab792UL, 0x4d98dda5UL, 0x46c49a98UL, - 0x4706f0afUL, 0x45404ef6UL, 0x448224c1UL, 0x41cd3244UL, 0x400f5873UL, - 0x4249e62aUL, 0x438b8c1dUL, 0x54f16850UL, 0x55330267UL, 0x5775bc3eUL, - 0x56b7d609UL, 0x53f8c08cUL, 0x523aaabbUL, 0x507c14e2UL, 0x51be7ed5UL, - 0x5ae239e8UL, 0x5b2053dfUL, 0x5966ed86UL, 0x58a487b1UL, 0x5deb9134UL, - 0x5c29fb03UL, 0x5e6f455aUL, 0x5fad2f6dUL, 0xe1351b80UL, 0xe0f771b7UL, - 0xe2b1cfeeUL, 0xe373a5d9UL, 0xe63cb35cUL, 0xe7fed96bUL, 0xe5b86732UL, - 0xe47a0d05UL, 0xef264a38UL, 0xeee4200fUL, 0xeca29e56UL, 0xed60f461UL, - 0xe82fe2e4UL, 0xe9ed88d3UL, 0xebab368aUL, 0xea695cbdUL, 0xfd13b8f0UL, - 0xfcd1d2c7UL, 0xfe976c9eUL, 0xff5506a9UL, 0xfa1a102cUL, 0xfbd87a1bUL, - 0xf99ec442UL, 0xf85cae75UL, 0xf300e948UL, 0xf2c2837fUL, 0xf0843d26UL, - 0xf1465711UL, 0xf4094194UL, 0xf5cb2ba3UL, 0xf78d95faUL, 0xf64fffcdUL, - 0xd9785d60UL, 0xd8ba3757UL, 0xdafc890eUL, 0xdb3ee339UL, 0xde71f5bcUL, - 0xdfb39f8bUL, 0xddf521d2UL, 0xdc374be5UL, 0xd76b0cd8UL, 0xd6a966efUL, - 0xd4efd8b6UL, 0xd52db281UL, 0xd062a404UL, 0xd1a0ce33UL, 0xd3e6706aUL, - 0xd2241a5dUL, 0xc55efe10UL, 0xc49c9427UL, 0xc6da2a7eUL, 0xc7184049UL, - 0xc25756ccUL, 0xc3953cfbUL, 0xc1d382a2UL, 0xc011e895UL, 0xcb4dafa8UL, - 0xca8fc59fUL, 0xc8c97bc6UL, 0xc90b11f1UL, 0xcc440774UL, 0xcd866d43UL, - 0xcfc0d31aUL, 0xce02b92dUL, 0x91af9640UL, 0x906dfc77UL, 0x922b422eUL, - 0x93e92819UL, 0x96a63e9cUL, 0x976454abUL, 0x9522eaf2UL, 0x94e080c5UL, - 0x9fbcc7f8UL, 0x9e7eadcfUL, 0x9c381396UL, 0x9dfa79a1UL, 0x98b56f24UL, - 0x99770513UL, 0x9b31bb4aUL, 0x9af3d17dUL, 0x8d893530UL, 0x8c4b5f07UL, - 0x8e0de15eUL, 0x8fcf8b69UL, 0x8a809decUL, 0x8b42f7dbUL, 0x89044982UL, - 0x88c623b5UL, 0x839a6488UL, 0x82580ebfUL, 0x801eb0e6UL, 0x81dcdad1UL, - 0x8493cc54UL, 0x8551a663UL, 0x8717183aUL, 0x86d5720dUL, 0xa9e2d0a0UL, - 0xa820ba97UL, 0xaa6604ceUL, 0xaba46ef9UL, 0xaeeb787cUL, 0xaf29124bUL, - 0xad6fac12UL, 0xacadc625UL, 0xa7f18118UL, 0xa633eb2fUL, 0xa4755576UL, - 0xa5b73f41UL, 0xa0f829c4UL, 0xa13a43f3UL, 0xa37cfdaaUL, 0xa2be979dUL, - 0xb5c473d0UL, 0xb40619e7UL, 0xb640a7beUL, 0xb782cd89UL, 0xb2cddb0cUL, - 0xb30fb13bUL, 0xb1490f62UL, 0xb08b6555UL, 0xbbd72268UL, 0xba15485fUL, - 0xb853f606UL, 0xb9919c31UL, 0xbcde8ab4UL, 0xbd1ce083UL, 0xbf5a5edaUL, - 0xbe9834edUL - }, - { - 0x00000000UL, 0xb8bc6765UL, 0xaa09c88bUL, 0x12b5afeeUL, 0x8f629757UL, - 0x37def032UL, 0x256b5fdcUL, 0x9dd738b9UL, 0xc5b428efUL, 0x7d084f8aUL, - 0x6fbde064UL, 0xd7018701UL, 0x4ad6bfb8UL, 0xf26ad8ddUL, 0xe0df7733UL, - 0x58631056UL, 0x5019579fUL, 0xe8a530faUL, 0xfa109f14UL, 0x42acf871UL, - 0xdf7bc0c8UL, 0x67c7a7adUL, 0x75720843UL, 0xcdce6f26UL, 0x95ad7f70UL, - 0x2d111815UL, 0x3fa4b7fbUL, 0x8718d09eUL, 0x1acfe827UL, 0xa2738f42UL, - 0xb0c620acUL, 0x087a47c9UL, 0xa032af3eUL, 0x188ec85bUL, 0x0a3b67b5UL, - 0xb28700d0UL, 0x2f503869UL, 0x97ec5f0cUL, 0x8559f0e2UL, 0x3de59787UL, - 0x658687d1UL, 0xdd3ae0b4UL, 0xcf8f4f5aUL, 0x7733283fUL, 0xeae41086UL, - 0x525877e3UL, 0x40edd80dUL, 0xf851bf68UL, 0xf02bf8a1UL, 0x48979fc4UL, - 0x5a22302aUL, 0xe29e574fUL, 0x7f496ff6UL, 0xc7f50893UL, 0xd540a77dUL, - 0x6dfcc018UL, 0x359fd04eUL, 0x8d23b72bUL, 0x9f9618c5UL, 0x272a7fa0UL, - 0xbafd4719UL, 0x0241207cUL, 0x10f48f92UL, 0xa848e8f7UL, 0x9b14583dUL, - 0x23a83f58UL, 0x311d90b6UL, 0x89a1f7d3UL, 0x1476cf6aUL, 0xaccaa80fUL, - 0xbe7f07e1UL, 0x06c36084UL, 0x5ea070d2UL, 0xe61c17b7UL, 0xf4a9b859UL, - 0x4c15df3cUL, 0xd1c2e785UL, 0x697e80e0UL, 0x7bcb2f0eUL, 0xc377486bUL, - 0xcb0d0fa2UL, 0x73b168c7UL, 0x6104c729UL, 0xd9b8a04cUL, 0x446f98f5UL, - 0xfcd3ff90UL, 0xee66507eUL, 0x56da371bUL, 0x0eb9274dUL, 0xb6054028UL, - 0xa4b0efc6UL, 0x1c0c88a3UL, 0x81dbb01aUL, 0x3967d77fUL, 0x2bd27891UL, - 0x936e1ff4UL, 0x3b26f703UL, 0x839a9066UL, 0x912f3f88UL, 0x299358edUL, - 0xb4446054UL, 0x0cf80731UL, 0x1e4da8dfUL, 0xa6f1cfbaUL, 0xfe92dfecUL, - 0x462eb889UL, 0x549b1767UL, 0xec277002UL, 0x71f048bbUL, 0xc94c2fdeUL, - 0xdbf98030UL, 0x6345e755UL, 0x6b3fa09cUL, 0xd383c7f9UL, 0xc1366817UL, - 0x798a0f72UL, 0xe45d37cbUL, 0x5ce150aeUL, 0x4e54ff40UL, 0xf6e89825UL, - 0xae8b8873UL, 0x1637ef16UL, 0x048240f8UL, 0xbc3e279dUL, 0x21e91f24UL, - 0x99557841UL, 0x8be0d7afUL, 0x335cb0caUL, 0xed59b63bUL, 0x55e5d15eUL, - 0x47507eb0UL, 0xffec19d5UL, 0x623b216cUL, 0xda874609UL, 0xc832e9e7UL, - 0x708e8e82UL, 0x28ed9ed4UL, 0x9051f9b1UL, 0x82e4565fUL, 0x3a58313aUL, - 0xa78f0983UL, 0x1f336ee6UL, 0x0d86c108UL, 0xb53aa66dUL, 0xbd40e1a4UL, - 0x05fc86c1UL, 0x1749292fUL, 0xaff54e4aUL, 0x322276f3UL, 0x8a9e1196UL, - 0x982bbe78UL, 0x2097d91dUL, 0x78f4c94bUL, 0xc048ae2eUL, 0xd2fd01c0UL, - 0x6a4166a5UL, 0xf7965e1cUL, 0x4f2a3979UL, 0x5d9f9697UL, 0xe523f1f2UL, - 0x4d6b1905UL, 0xf5d77e60UL, 0xe762d18eUL, 0x5fdeb6ebUL, 0xc2098e52UL, - 0x7ab5e937UL, 0x680046d9UL, 0xd0bc21bcUL, 0x88df31eaUL, 0x3063568fUL, - 0x22d6f961UL, 0x9a6a9e04UL, 0x07bda6bdUL, 0xbf01c1d8UL, 0xadb46e36UL, - 0x15080953UL, 0x1d724e9aUL, 0xa5ce29ffUL, 0xb77b8611UL, 0x0fc7e174UL, - 0x9210d9cdUL, 0x2aacbea8UL, 0x38191146UL, 0x80a57623UL, 0xd8c66675UL, - 0x607a0110UL, 0x72cfaefeUL, 0xca73c99bUL, 0x57a4f122UL, 0xef189647UL, - 0xfdad39a9UL, 0x45115eccUL, 0x764dee06UL, 0xcef18963UL, 0xdc44268dUL, - 0x64f841e8UL, 0xf92f7951UL, 0x41931e34UL, 0x5326b1daUL, 0xeb9ad6bfUL, - 0xb3f9c6e9UL, 0x0b45a18cUL, 0x19f00e62UL, 0xa14c6907UL, 0x3c9b51beUL, - 0x842736dbUL, 0x96929935UL, 0x2e2efe50UL, 0x2654b999UL, 0x9ee8defcUL, - 0x8c5d7112UL, 0x34e11677UL, 0xa9362eceUL, 0x118a49abUL, 0x033fe645UL, - 0xbb838120UL, 0xe3e09176UL, 0x5b5cf613UL, 0x49e959fdUL, 0xf1553e98UL, - 0x6c820621UL, 0xd43e6144UL, 0xc68bceaaUL, 0x7e37a9cfUL, 0xd67f4138UL, - 0x6ec3265dUL, 0x7c7689b3UL, 0xc4caeed6UL, 0x591dd66fUL, 0xe1a1b10aUL, - 0xf3141ee4UL, 0x4ba87981UL, 0x13cb69d7UL, 0xab770eb2UL, 0xb9c2a15cUL, - 0x017ec639UL, 0x9ca9fe80UL, 0x241599e5UL, 0x36a0360bUL, 0x8e1c516eUL, - 0x866616a7UL, 0x3eda71c2UL, 0x2c6fde2cUL, 0x94d3b949UL, 0x090481f0UL, - 0xb1b8e695UL, 0xa30d497bUL, 0x1bb12e1eUL, 0x43d23e48UL, 0xfb6e592dUL, - 0xe9dbf6c3UL, 0x516791a6UL, 0xccb0a91fUL, 0x740cce7aUL, 0x66b96194UL, - 0xde0506f1UL - }, - { - 0x00000000UL, 0x96300777UL, 0x2c610eeeUL, 0xba510999UL, 0x19c46d07UL, - 0x8ff46a70UL, 0x35a563e9UL, 0xa395649eUL, 0x3288db0eUL, 0xa4b8dc79UL, - 0x1ee9d5e0UL, 0x88d9d297UL, 0x2b4cb609UL, 0xbd7cb17eUL, 0x072db8e7UL, - 0x911dbf90UL, 0x6410b71dUL, 0xf220b06aUL, 0x4871b9f3UL, 0xde41be84UL, - 0x7dd4da1aUL, 0xebe4dd6dUL, 0x51b5d4f4UL, 0xc785d383UL, 0x56986c13UL, - 0xc0a86b64UL, 0x7af962fdUL, 0xecc9658aUL, 0x4f5c0114UL, 0xd96c0663UL, - 0x633d0ffaUL, 0xf50d088dUL, 0xc8206e3bUL, 0x5e10694cUL, 0xe44160d5UL, - 0x727167a2UL, 0xd1e4033cUL, 0x47d4044bUL, 0xfd850dd2UL, 0x6bb50aa5UL, - 0xfaa8b535UL, 0x6c98b242UL, 0xd6c9bbdbUL, 0x40f9bcacUL, 0xe36cd832UL, - 0x755cdf45UL, 0xcf0dd6dcUL, 0x593dd1abUL, 0xac30d926UL, 0x3a00de51UL, - 0x8051d7c8UL, 0x1661d0bfUL, 0xb5f4b421UL, 0x23c4b356UL, 0x9995bacfUL, - 0x0fa5bdb8UL, 0x9eb80228UL, 0x0888055fUL, 0xb2d90cc6UL, 0x24e90bb1UL, - 0x877c6f2fUL, 0x114c6858UL, 0xab1d61c1UL, 0x3d2d66b6UL, 0x9041dc76UL, - 0x0671db01UL, 0xbc20d298UL, 0x2a10d5efUL, 0x8985b171UL, 0x1fb5b606UL, - 0xa5e4bf9fUL, 0x33d4b8e8UL, 0xa2c90778UL, 0x34f9000fUL, 0x8ea80996UL, - 0x18980ee1UL, 0xbb0d6a7fUL, 0x2d3d6d08UL, 0x976c6491UL, 0x015c63e6UL, - 0xf4516b6bUL, 0x62616c1cUL, 0xd8306585UL, 0x4e0062f2UL, 0xed95066cUL, - 0x7ba5011bUL, 0xc1f40882UL, 0x57c40ff5UL, 0xc6d9b065UL, 0x50e9b712UL, - 0xeab8be8bUL, 0x7c88b9fcUL, 0xdf1ddd62UL, 0x492dda15UL, 0xf37cd38cUL, - 0x654cd4fbUL, 0x5861b24dUL, 0xce51b53aUL, 0x7400bca3UL, 0xe230bbd4UL, - 0x41a5df4aUL, 0xd795d83dUL, 0x6dc4d1a4UL, 0xfbf4d6d3UL, 0x6ae96943UL, - 0xfcd96e34UL, 0x468867adUL, 0xd0b860daUL, 0x732d0444UL, 0xe51d0333UL, - 0x5f4c0aaaUL, 0xc97c0dddUL, 0x3c710550UL, 0xaa410227UL, 0x10100bbeUL, - 0x86200cc9UL, 0x25b56857UL, 0xb3856f20UL, 0x09d466b9UL, 0x9fe461ceUL, - 0x0ef9de5eUL, 0x98c9d929UL, 0x2298d0b0UL, 0xb4a8d7c7UL, 0x173db359UL, - 0x810db42eUL, 0x3b5cbdb7UL, 0xad6cbac0UL, 0x2083b8edUL, 0xb6b3bf9aUL, - 0x0ce2b603UL, 0x9ad2b174UL, 0x3947d5eaUL, 0xaf77d29dUL, 0x1526db04UL, - 0x8316dc73UL, 0x120b63e3UL, 0x843b6494UL, 0x3e6a6d0dUL, 0xa85a6a7aUL, - 0x0bcf0ee4UL, 0x9dff0993UL, 0x27ae000aUL, 0xb19e077dUL, 0x44930ff0UL, - 0xd2a30887UL, 0x68f2011eUL, 0xfec20669UL, 0x5d5762f7UL, 0xcb676580UL, - 0x71366c19UL, 0xe7066b6eUL, 0x761bd4feUL, 0xe02bd389UL, 0x5a7ada10UL, - 0xcc4add67UL, 0x6fdfb9f9UL, 0xf9efbe8eUL, 0x43beb717UL, 0xd58eb060UL, - 0xe8a3d6d6UL, 0x7e93d1a1UL, 0xc4c2d838UL, 0x52f2df4fUL, 0xf167bbd1UL, - 0x6757bca6UL, 0xdd06b53fUL, 0x4b36b248UL, 0xda2b0dd8UL, 0x4c1b0aafUL, - 0xf64a0336UL, 0x607a0441UL, 0xc3ef60dfUL, 0x55df67a8UL, 0xef8e6e31UL, - 0x79be6946UL, 0x8cb361cbUL, 0x1a8366bcUL, 0xa0d26f25UL, 0x36e26852UL, - 0x95770cccUL, 0x03470bbbUL, 0xb9160222UL, 0x2f260555UL, 0xbe3bbac5UL, - 0x280bbdb2UL, 0x925ab42bUL, 0x046ab35cUL, 0xa7ffd7c2UL, 0x31cfd0b5UL, - 0x8b9ed92cUL, 0x1daede5bUL, 0xb0c2649bUL, 0x26f263ecUL, 0x9ca36a75UL, - 0x0a936d02UL, 0xa906099cUL, 0x3f360eebUL, 0x85670772UL, 0x13570005UL, - 0x824abf95UL, 0x147ab8e2UL, 0xae2bb17bUL, 0x381bb60cUL, 0x9b8ed292UL, - 0x0dbed5e5UL, 0xb7efdc7cUL, 0x21dfdb0bUL, 0xd4d2d386UL, 0x42e2d4f1UL, - 0xf8b3dd68UL, 0x6e83da1fUL, 0xcd16be81UL, 0x5b26b9f6UL, 0xe177b06fUL, - 0x7747b718UL, 0xe65a0888UL, 0x706a0fffUL, 0xca3b0666UL, 0x5c0b0111UL, - 0xff9e658fUL, 0x69ae62f8UL, 0xd3ff6b61UL, 0x45cf6c16UL, 0x78e20aa0UL, - 0xeed20dd7UL, 0x5483044eUL, 0xc2b30339UL, 0x612667a7UL, 0xf71660d0UL, - 0x4d476949UL, 0xdb776e3eUL, 0x4a6ad1aeUL, 0xdc5ad6d9UL, 0x660bdf40UL, - 0xf03bd837UL, 0x53aebca9UL, 0xc59ebbdeUL, 0x7fcfb247UL, 0xe9ffb530UL, - 0x1cf2bdbdUL, 0x8ac2bacaUL, 0x3093b353UL, 0xa6a3b424UL, 0x0536d0baUL, - 0x9306d7cdUL, 0x2957de54UL, 0xbf67d923UL, 0x2e7a66b3UL, 0xb84a61c4UL, - 0x021b685dUL, 0x942b6f2aUL, 0x37be0bb4UL, 0xa18e0cc3UL, 0x1bdf055aUL, - 0x8def022dUL - }, - { - 0x00000000UL, 0x41311b19UL, 0x82623632UL, 0xc3532d2bUL, 0x04c56c64UL, - 0x45f4777dUL, 0x86a75a56UL, 0xc796414fUL, 0x088ad9c8UL, 0x49bbc2d1UL, - 0x8ae8effaUL, 0xcbd9f4e3UL, 0x0c4fb5acUL, 0x4d7eaeb5UL, 0x8e2d839eUL, - 0xcf1c9887UL, 0x5112c24aUL, 0x1023d953UL, 0xd370f478UL, 0x9241ef61UL, - 0x55d7ae2eUL, 0x14e6b537UL, 0xd7b5981cUL, 0x96848305UL, 0x59981b82UL, - 0x18a9009bUL, 0xdbfa2db0UL, 0x9acb36a9UL, 0x5d5d77e6UL, 0x1c6c6cffUL, - 0xdf3f41d4UL, 0x9e0e5acdUL, 0xa2248495UL, 0xe3159f8cUL, 0x2046b2a7UL, - 0x6177a9beUL, 0xa6e1e8f1UL, 0xe7d0f3e8UL, 0x2483dec3UL, 0x65b2c5daUL, - 0xaaae5d5dUL, 0xeb9f4644UL, 0x28cc6b6fUL, 0x69fd7076UL, 0xae6b3139UL, - 0xef5a2a20UL, 0x2c09070bUL, 0x6d381c12UL, 0xf33646dfUL, 0xb2075dc6UL, - 0x715470edUL, 0x30656bf4UL, 0xf7f32abbUL, 0xb6c231a2UL, 0x75911c89UL, - 0x34a00790UL, 0xfbbc9f17UL, 0xba8d840eUL, 0x79dea925UL, 0x38efb23cUL, - 0xff79f373UL, 0xbe48e86aUL, 0x7d1bc541UL, 0x3c2ade58UL, 0x054f79f0UL, - 0x447e62e9UL, 0x872d4fc2UL, 0xc61c54dbUL, 0x018a1594UL, 0x40bb0e8dUL, - 0x83e823a6UL, 0xc2d938bfUL, 0x0dc5a038UL, 0x4cf4bb21UL, 0x8fa7960aUL, - 0xce968d13UL, 0x0900cc5cUL, 0x4831d745UL, 0x8b62fa6eUL, 0xca53e177UL, - 0x545dbbbaUL, 0x156ca0a3UL, 0xd63f8d88UL, 0x970e9691UL, 0x5098d7deUL, - 0x11a9ccc7UL, 0xd2fae1ecUL, 0x93cbfaf5UL, 0x5cd76272UL, 0x1de6796bUL, - 0xdeb55440UL, 0x9f844f59UL, 0x58120e16UL, 0x1923150fUL, 0xda703824UL, - 0x9b41233dUL, 0xa76bfd65UL, 0xe65ae67cUL, 0x2509cb57UL, 0x6438d04eUL, - 0xa3ae9101UL, 0xe29f8a18UL, 0x21cca733UL, 0x60fdbc2aUL, 0xafe124adUL, - 0xeed03fb4UL, 0x2d83129fUL, 0x6cb20986UL, 0xab2448c9UL, 0xea1553d0UL, - 0x29467efbUL, 0x687765e2UL, 0xf6793f2fUL, 0xb7482436UL, 0x741b091dUL, - 0x352a1204UL, 0xf2bc534bUL, 0xb38d4852UL, 0x70de6579UL, 0x31ef7e60UL, - 0xfef3e6e7UL, 0xbfc2fdfeUL, 0x7c91d0d5UL, 0x3da0cbccUL, 0xfa368a83UL, - 0xbb07919aUL, 0x7854bcb1UL, 0x3965a7a8UL, 0x4b98833bUL, 0x0aa99822UL, - 0xc9fab509UL, 0x88cbae10UL, 0x4f5def5fUL, 0x0e6cf446UL, 0xcd3fd96dUL, - 0x8c0ec274UL, 0x43125af3UL, 0x022341eaUL, 0xc1706cc1UL, 0x804177d8UL, - 0x47d73697UL, 0x06e62d8eUL, 0xc5b500a5UL, 0x84841bbcUL, 0x1a8a4171UL, - 0x5bbb5a68UL, 0x98e87743UL, 0xd9d96c5aUL, 0x1e4f2d15UL, 0x5f7e360cUL, - 0x9c2d1b27UL, 0xdd1c003eUL, 0x120098b9UL, 0x533183a0UL, 0x9062ae8bUL, - 0xd153b592UL, 0x16c5f4ddUL, 0x57f4efc4UL, 0x94a7c2efUL, 0xd596d9f6UL, - 0xe9bc07aeUL, 0xa88d1cb7UL, 0x6bde319cUL, 0x2aef2a85UL, 0xed796bcaUL, - 0xac4870d3UL, 0x6f1b5df8UL, 0x2e2a46e1UL, 0xe136de66UL, 0xa007c57fUL, - 0x6354e854UL, 0x2265f34dUL, 0xe5f3b202UL, 0xa4c2a91bUL, 0x67918430UL, - 0x26a09f29UL, 0xb8aec5e4UL, 0xf99fdefdUL, 0x3accf3d6UL, 0x7bfde8cfUL, - 0xbc6ba980UL, 0xfd5ab299UL, 0x3e099fb2UL, 0x7f3884abUL, 0xb0241c2cUL, - 0xf1150735UL, 0x32462a1eUL, 0x73773107UL, 0xb4e17048UL, 0xf5d06b51UL, - 0x3683467aUL, 0x77b25d63UL, 0x4ed7facbUL, 0x0fe6e1d2UL, 0xccb5ccf9UL, - 0x8d84d7e0UL, 0x4a1296afUL, 0x0b238db6UL, 0xc870a09dUL, 0x8941bb84UL, - 0x465d2303UL, 0x076c381aUL, 0xc43f1531UL, 0x850e0e28UL, 0x42984f67UL, - 0x03a9547eUL, 0xc0fa7955UL, 0x81cb624cUL, 0x1fc53881UL, 0x5ef42398UL, - 0x9da70eb3UL, 0xdc9615aaUL, 0x1b0054e5UL, 0x5a314ffcUL, 0x996262d7UL, - 0xd85379ceUL, 0x174fe149UL, 0x567efa50UL, 0x952dd77bUL, 0xd41ccc62UL, - 0x138a8d2dUL, 0x52bb9634UL, 0x91e8bb1fUL, 0xd0d9a006UL, 0xecf37e5eUL, - 0xadc26547UL, 0x6e91486cUL, 0x2fa05375UL, 0xe836123aUL, 0xa9070923UL, - 0x6a542408UL, 0x2b653f11UL, 0xe479a796UL, 0xa548bc8fUL, 0x661b91a4UL, - 0x272a8abdUL, 0xe0bccbf2UL, 0xa18dd0ebUL, 0x62defdc0UL, 0x23efe6d9UL, - 0xbde1bc14UL, 0xfcd0a70dUL, 0x3f838a26UL, 0x7eb2913fUL, 0xb924d070UL, - 0xf815cb69UL, 0x3b46e642UL, 0x7a77fd5bUL, 0xb56b65dcUL, 0xf45a7ec5UL, - 0x370953eeUL, 0x763848f7UL, 0xb1ae09b8UL, 0xf09f12a1UL, 0x33cc3f8aUL, - 0x72fd2493UL - }, - { - 0x00000000UL, 0x376ac201UL, 0x6ed48403UL, 0x59be4602UL, 0xdca80907UL, - 0xebc2cb06UL, 0xb27c8d04UL, 0x85164f05UL, 0xb851130eUL, 0x8f3bd10fUL, - 0xd685970dUL, 0xe1ef550cUL, 0x64f91a09UL, 0x5393d808UL, 0x0a2d9e0aUL, - 0x3d475c0bUL, 0x70a3261cUL, 0x47c9e41dUL, 0x1e77a21fUL, 0x291d601eUL, - 0xac0b2f1bUL, 0x9b61ed1aUL, 0xc2dfab18UL, 0xf5b56919UL, 0xc8f23512UL, - 0xff98f713UL, 0xa626b111UL, 0x914c7310UL, 0x145a3c15UL, 0x2330fe14UL, - 0x7a8eb816UL, 0x4de47a17UL, 0xe0464d38UL, 0xd72c8f39UL, 0x8e92c93bUL, - 0xb9f80b3aUL, 0x3cee443fUL, 0x0b84863eUL, 0x523ac03cUL, 0x6550023dUL, - 0x58175e36UL, 0x6f7d9c37UL, 0x36c3da35UL, 0x01a91834UL, 0x84bf5731UL, - 0xb3d59530UL, 0xea6bd332UL, 0xdd011133UL, 0x90e56b24UL, 0xa78fa925UL, - 0xfe31ef27UL, 0xc95b2d26UL, 0x4c4d6223UL, 0x7b27a022UL, 0x2299e620UL, - 0x15f32421UL, 0x28b4782aUL, 0x1fdeba2bUL, 0x4660fc29UL, 0x710a3e28UL, - 0xf41c712dUL, 0xc376b32cUL, 0x9ac8f52eUL, 0xada2372fUL, 0xc08d9a70UL, - 0xf7e75871UL, 0xae591e73UL, 0x9933dc72UL, 0x1c259377UL, 0x2b4f5176UL, - 0x72f11774UL, 0x459bd575UL, 0x78dc897eUL, 0x4fb64b7fUL, 0x16080d7dUL, - 0x2162cf7cUL, 0xa4748079UL, 0x931e4278UL, 0xcaa0047aUL, 0xfdcac67bUL, - 0xb02ebc6cUL, 0x87447e6dUL, 0xdefa386fUL, 0xe990fa6eUL, 0x6c86b56bUL, - 0x5bec776aUL, 0x02523168UL, 0x3538f369UL, 0x087faf62UL, 0x3f156d63UL, - 0x66ab2b61UL, 0x51c1e960UL, 0xd4d7a665UL, 0xe3bd6464UL, 0xba032266UL, - 0x8d69e067UL, 0x20cbd748UL, 0x17a11549UL, 0x4e1f534bUL, 0x7975914aUL, - 0xfc63de4fUL, 0xcb091c4eUL, 0x92b75a4cUL, 0xa5dd984dUL, 0x989ac446UL, - 0xaff00647UL, 0xf64e4045UL, 0xc1248244UL, 0x4432cd41UL, 0x73580f40UL, - 0x2ae64942UL, 0x1d8c8b43UL, 0x5068f154UL, 0x67023355UL, 0x3ebc7557UL, - 0x09d6b756UL, 0x8cc0f853UL, 0xbbaa3a52UL, 0xe2147c50UL, 0xd57ebe51UL, - 0xe839e25aUL, 0xdf53205bUL, 0x86ed6659UL, 0xb187a458UL, 0x3491eb5dUL, - 0x03fb295cUL, 0x5a456f5eUL, 0x6d2fad5fUL, 0x801b35e1UL, 0xb771f7e0UL, - 0xeecfb1e2UL, 0xd9a573e3UL, 0x5cb33ce6UL, 0x6bd9fee7UL, 0x3267b8e5UL, - 0x050d7ae4UL, 0x384a26efUL, 0x0f20e4eeUL, 0x569ea2ecUL, 0x61f460edUL, - 0xe4e22fe8UL, 0xd388ede9UL, 0x8a36abebUL, 0xbd5c69eaUL, 0xf0b813fdUL, - 0xc7d2d1fcUL, 0x9e6c97feUL, 0xa90655ffUL, 0x2c101afaUL, 0x1b7ad8fbUL, - 0x42c49ef9UL, 0x75ae5cf8UL, 0x48e900f3UL, 0x7f83c2f2UL, 0x263d84f0UL, - 0x115746f1UL, 0x944109f4UL, 0xa32bcbf5UL, 0xfa958df7UL, 0xcdff4ff6UL, - 0x605d78d9UL, 0x5737bad8UL, 0x0e89fcdaUL, 0x39e33edbUL, 0xbcf571deUL, - 0x8b9fb3dfUL, 0xd221f5ddUL, 0xe54b37dcUL, 0xd80c6bd7UL, 0xef66a9d6UL, - 0xb6d8efd4UL, 0x81b22dd5UL, 0x04a462d0UL, 0x33cea0d1UL, 0x6a70e6d3UL, - 0x5d1a24d2UL, 0x10fe5ec5UL, 0x27949cc4UL, 0x7e2adac6UL, 0x494018c7UL, - 0xcc5657c2UL, 0xfb3c95c3UL, 0xa282d3c1UL, 0x95e811c0UL, 0xa8af4dcbUL, - 0x9fc58fcaUL, 0xc67bc9c8UL, 0xf1110bc9UL, 0x740744ccUL, 0x436d86cdUL, - 0x1ad3c0cfUL, 0x2db902ceUL, 0x4096af91UL, 0x77fc6d90UL, 0x2e422b92UL, - 0x1928e993UL, 0x9c3ea696UL, 0xab546497UL, 0xf2ea2295UL, 0xc580e094UL, - 0xf8c7bc9fUL, 0xcfad7e9eUL, 0x9613389cUL, 0xa179fa9dUL, 0x246fb598UL, - 0x13057799UL, 0x4abb319bUL, 0x7dd1f39aUL, 0x3035898dUL, 0x075f4b8cUL, - 0x5ee10d8eUL, 0x698bcf8fUL, 0xec9d808aUL, 0xdbf7428bUL, 0x82490489UL, - 0xb523c688UL, 0x88649a83UL, 0xbf0e5882UL, 0xe6b01e80UL, 0xd1dadc81UL, - 0x54cc9384UL, 0x63a65185UL, 0x3a181787UL, 0x0d72d586UL, 0xa0d0e2a9UL, - 0x97ba20a8UL, 0xce0466aaUL, 0xf96ea4abUL, 0x7c78ebaeUL, 0x4b1229afUL, - 0x12ac6fadUL, 0x25c6adacUL, 0x1881f1a7UL, 0x2feb33a6UL, 0x765575a4UL, - 0x413fb7a5UL, 0xc429f8a0UL, 0xf3433aa1UL, 0xaafd7ca3UL, 0x9d97bea2UL, - 0xd073c4b5UL, 0xe71906b4UL, 0xbea740b6UL, 0x89cd82b7UL, 0x0cdbcdb2UL, - 0x3bb10fb3UL, 0x620f49b1UL, 0x55658bb0UL, 0x6822d7bbUL, 0x5f4815baUL, - 0x06f653b8UL, 0x319c91b9UL, 0xb48adebcUL, 0x83e01cbdUL, 0xda5e5abfUL, - 0xed3498beUL - }, - { - 0x00000000UL, 0x6567bcb8UL, 0x8bc809aaUL, 0xeeafb512UL, 0x5797628fUL, - 0x32f0de37UL, 0xdc5f6b25UL, 0xb938d79dUL, 0xef28b4c5UL, 0x8a4f087dUL, - 0x64e0bd6fUL, 0x018701d7UL, 0xb8bfd64aUL, 0xddd86af2UL, 0x3377dfe0UL, - 0x56106358UL, 0x9f571950UL, 0xfa30a5e8UL, 0x149f10faUL, 0x71f8ac42UL, - 0xc8c07bdfUL, 0xada7c767UL, 0x43087275UL, 0x266fcecdUL, 0x707fad95UL, - 0x1518112dUL, 0xfbb7a43fUL, 0x9ed01887UL, 0x27e8cf1aUL, 0x428f73a2UL, - 0xac20c6b0UL, 0xc9477a08UL, 0x3eaf32a0UL, 0x5bc88e18UL, 0xb5673b0aUL, - 0xd00087b2UL, 0x6938502fUL, 0x0c5fec97UL, 0xe2f05985UL, 0x8797e53dUL, - 0xd1878665UL, 0xb4e03addUL, 0x5a4f8fcfUL, 0x3f283377UL, 0x8610e4eaUL, - 0xe3775852UL, 0x0dd8ed40UL, 0x68bf51f8UL, 0xa1f82bf0UL, 0xc49f9748UL, - 0x2a30225aUL, 0x4f579ee2UL, 0xf66f497fUL, 0x9308f5c7UL, 0x7da740d5UL, - 0x18c0fc6dUL, 0x4ed09f35UL, 0x2bb7238dUL, 0xc518969fUL, 0xa07f2a27UL, - 0x1947fdbaUL, 0x7c204102UL, 0x928ff410UL, 0xf7e848a8UL, 0x3d58149bUL, - 0x583fa823UL, 0xb6901d31UL, 0xd3f7a189UL, 0x6acf7614UL, 0x0fa8caacUL, - 0xe1077fbeUL, 0x8460c306UL, 0xd270a05eUL, 0xb7171ce6UL, 0x59b8a9f4UL, - 0x3cdf154cUL, 0x85e7c2d1UL, 0xe0807e69UL, 0x0e2fcb7bUL, 0x6b4877c3UL, - 0xa20f0dcbUL, 0xc768b173UL, 0x29c70461UL, 0x4ca0b8d9UL, 0xf5986f44UL, - 0x90ffd3fcUL, 0x7e5066eeUL, 0x1b37da56UL, 0x4d27b90eUL, 0x284005b6UL, - 0xc6efb0a4UL, 0xa3880c1cUL, 0x1ab0db81UL, 0x7fd76739UL, 0x9178d22bUL, - 0xf41f6e93UL, 0x03f7263bUL, 0x66909a83UL, 0x883f2f91UL, 0xed589329UL, - 0x546044b4UL, 0x3107f80cUL, 0xdfa84d1eUL, 0xbacff1a6UL, 0xecdf92feUL, - 0x89b82e46UL, 0x67179b54UL, 0x027027ecUL, 0xbb48f071UL, 0xde2f4cc9UL, - 0x3080f9dbUL, 0x55e74563UL, 0x9ca03f6bUL, 0xf9c783d3UL, 0x176836c1UL, - 0x720f8a79UL, 0xcb375de4UL, 0xae50e15cUL, 0x40ff544eUL, 0x2598e8f6UL, - 0x73888baeUL, 0x16ef3716UL, 0xf8408204UL, 0x9d273ebcUL, 0x241fe921UL, - 0x41785599UL, 0xafd7e08bUL, 0xcab05c33UL, 0x3bb659edUL, 0x5ed1e555UL, - 0xb07e5047UL, 0xd519ecffUL, 0x6c213b62UL, 0x094687daUL, 0xe7e932c8UL, - 0x828e8e70UL, 0xd49eed28UL, 0xb1f95190UL, 0x5f56e482UL, 0x3a31583aUL, - 0x83098fa7UL, 0xe66e331fUL, 0x08c1860dUL, 0x6da63ab5UL, 0xa4e140bdUL, - 0xc186fc05UL, 0x2f294917UL, 0x4a4ef5afUL, 0xf3762232UL, 0x96119e8aUL, - 0x78be2b98UL, 0x1dd99720UL, 0x4bc9f478UL, 0x2eae48c0UL, 0xc001fdd2UL, - 0xa566416aUL, 0x1c5e96f7UL, 0x79392a4fUL, 0x97969f5dUL, 0xf2f123e5UL, - 0x05196b4dUL, 0x607ed7f5UL, 0x8ed162e7UL, 0xebb6de5fUL, 0x528e09c2UL, - 0x37e9b57aUL, 0xd9460068UL, 0xbc21bcd0UL, 0xea31df88UL, 0x8f566330UL, - 0x61f9d622UL, 0x049e6a9aUL, 0xbda6bd07UL, 0xd8c101bfUL, 0x366eb4adUL, - 0x53090815UL, 0x9a4e721dUL, 0xff29cea5UL, 0x11867bb7UL, 0x74e1c70fUL, - 0xcdd91092UL, 0xa8beac2aUL, 0x46111938UL, 0x2376a580UL, 0x7566c6d8UL, - 0x10017a60UL, 0xfeaecf72UL, 0x9bc973caUL, 0x22f1a457UL, 0x479618efUL, - 0xa939adfdUL, 0xcc5e1145UL, 0x06ee4d76UL, 0x6389f1ceUL, 0x8d2644dcUL, - 0xe841f864UL, 0x51792ff9UL, 0x341e9341UL, 0xdab12653UL, 0xbfd69aebUL, - 0xe9c6f9b3UL, 0x8ca1450bUL, 0x620ef019UL, 0x07694ca1UL, 0xbe519b3cUL, - 0xdb362784UL, 0x35999296UL, 0x50fe2e2eUL, 0x99b95426UL, 0xfcdee89eUL, - 0x12715d8cUL, 0x7716e134UL, 0xce2e36a9UL, 0xab498a11UL, 0x45e63f03UL, - 0x208183bbUL, 0x7691e0e3UL, 0x13f65c5bUL, 0xfd59e949UL, 0x983e55f1UL, - 0x2106826cUL, 0x44613ed4UL, 0xaace8bc6UL, 0xcfa9377eUL, 0x38417fd6UL, - 0x5d26c36eUL, 0xb389767cUL, 0xd6eecac4UL, 0x6fd61d59UL, 0x0ab1a1e1UL, - 0xe41e14f3UL, 0x8179a84bUL, 0xd769cb13UL, 0xb20e77abUL, 0x5ca1c2b9UL, - 0x39c67e01UL, 0x80fea99cUL, 0xe5991524UL, 0x0b36a036UL, 0x6e511c8eUL, - 0xa7166686UL, 0xc271da3eUL, 0x2cde6f2cUL, 0x49b9d394UL, 0xf0810409UL, - 0x95e6b8b1UL, 0x7b490da3UL, 0x1e2eb11bUL, 0x483ed243UL, 0x2d596efbUL, - 0xc3f6dbe9UL, 0xa6916751UL, 0x1fa9b0ccUL, 0x7ace0c74UL, 0x9461b966UL, - 0xf10605deUL -#endif - } -}; diff --git a/sourcepawn/third_party/zlib/deflate.c b/sourcepawn/third_party/zlib/deflate.c deleted file mode 100644 index f58dee25..00000000 --- a/sourcepawn/third_party/zlib/deflate.c +++ /dev/null @@ -1,1737 +0,0 @@ -/* deflate.c -- compress data using the deflation algorithm - * Copyright (C) 1995-2005 Jean-loup Gailly. - * For conditions of distribution and use, see copyright notice in zlib.h - */ - -/* - * ALGORITHM - * - * The "deflation" process depends on being able to identify portions - * of the input text which are identical to earlier input (within a - * sliding window trailing behind the input currently being processed). - * - * The most straightforward technique turns out to be the fastest for - * most input files: try all possible matches and select the longest. - * The key feature of this algorithm is that insertions into the string - * dictionary are very simple and thus fast, and deletions are avoided - * completely. Insertions are performed at each input character, whereas - * string matches are performed only when the previous match ends. So it - * is preferable to spend more time in matches to allow very fast string - * insertions and avoid deletions. The matching algorithm for small - * strings is inspired from that of Rabin & Karp. A brute force approach - * is used to find longer strings when a small match has been found. - * A similar algorithm is used in comic (by Jan-Mark Wams) and freeze - * (by Leonid Broukhis). - * A previous version of this file used a more sophisticated algorithm - * (by Fiala and Greene) which is guaranteed to run in linear amortized - * time, but has a larger average cost, uses more memory and is patented. - * However the F&G algorithm may be faster for some highly redundant - * files if the parameter max_chain_length (described below) is too large. - * - * ACKNOWLEDGEMENTS - * - * The idea of lazy evaluation of matches is due to Jan-Mark Wams, and - * I found it in 'freeze' written by Leonid Broukhis. - * Thanks to many people for bug reports and testing. - * - * REFERENCES - * - * Deutsch, L.P.,"DEFLATE Compressed Data Format Specification". - * Available in http://www.ietf.org/rfc/rfc1951.txt - * - * A description of the Rabin and Karp algorithm is given in the book - * "Algorithms" by R. Sedgewick, Addison-Wesley, p252. - * - * Fiala,E.R., and Greene,D.H. - * Data Compression with Finite Windows, Comm.ACM, 32,4 (1989) 490-595 - * - */ - -/* @(#) $Id$ */ - -#include -#include "deflate.h" - -const char deflate_copyright[] = - " deflate 1.2.3 Copyright 1995-2005 Jean-loup Gailly "; -/* - If you use the zlib library in a product, an acknowledgment is welcome - in the documentation of your product. If for some reason you cannot - include such an acknowledgment, I would appreciate that you keep this - copyright string in the executable of your product. - */ - -/* =========================================================================== - * Function prototypes. - */ -typedef enum { - need_more, /* block not completed, need more input or more output */ - block_done, /* block flush performed */ - finish_started, /* finish started, need only more output at next deflate */ - finish_done /* finish done, accept no more input or output */ -} block_state; - -typedef block_state (*compress_func) OF((deflate_state *s, int flush)); -/* Compression function. Returns the block state after the call. */ - -local void fill_window OF((deflate_state *s)); -local block_state deflate_stored OF((deflate_state *s, int flush)); -local block_state deflate_fast OF((deflate_state *s, int flush)); -#ifndef FASTEST -local block_state deflate_slow OF((deflate_state *s, int flush)); -#endif -local void lm_init OF((deflate_state *s)); -local void putShortMSB OF((deflate_state *s, uInt b)); -local void flush_pending OF((z_streamp strm)); -local int read_buf OF((z_streamp strm, Bytef *buf, unsigned size)); -#ifndef FASTEST -#ifdef ASMV - void match_init OF((void)); /* asm code initialization */ - uInt longest_match OF((deflate_state *s, IPos cur_match)); -#else -local uInt longest_match OF((deflate_state *s, IPos cur_match)); -#endif -#endif -local uInt longest_match_fast OF((deflate_state *s, IPos cur_match)); - -#ifdef DEBUG -local void check_match OF((deflate_state *s, IPos start, IPos match, - int length)); -#endif - -/* =========================================================================== - * Local data - */ - -#define NIL 0 -/* Tail of hash chains */ - -#ifndef TOO_FAR -# define TOO_FAR 4096 -#endif -/* Matches of length 3 are discarded if their distance exceeds TOO_FAR */ - -#define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1) -/* Minimum amount of lookahead, except at the end of the input file. - * See deflate.c for comments about the MIN_MATCH+1. - */ - -/* Values for max_lazy_match, good_match and max_chain_length, depending on - * the desired pack level (0..9). The values given below have been tuned to - * exclude worst case performance for pathological files. Better values may be - * found for specific files. - */ -typedef struct config_s { - ush good_length; /* reduce lazy search above this match length */ - ush max_lazy; /* do not perform lazy search above this match length */ - ush nice_length; /* quit search above this match length */ - ush max_chain; - compress_func func; -} config; - -#ifdef FASTEST -local const config configuration_table[2] = { -/* good lazy nice chain */ -/* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */ -/* 1 */ {4, 4, 8, 4, deflate_fast}}; /* max speed, no lazy matches */ -#else -local const config configuration_table[10] = { -/* good lazy nice chain */ -/* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */ -/* 1 */ {4, 4, 8, 4, deflate_fast}, /* max speed, no lazy matches */ -/* 2 */ {4, 5, 16, 8, deflate_fast}, -/* 3 */ {4, 6, 32, 32, deflate_fast}, - -/* 4 */ {4, 4, 16, 16, deflate_slow}, /* lazy matches */ -/* 5 */ {8, 16, 32, 32, deflate_slow}, -/* 6 */ {8, 16, 128, 128, deflate_slow}, -/* 7 */ {8, 32, 128, 256, deflate_slow}, -/* 8 */ {32, 128, 258, 1024, deflate_slow}, -/* 9 */ {32, 258, 258, 4096, deflate_slow}}; /* max compression */ -#endif - -/* Note: the deflate() code requires max_lazy >= MIN_MATCH and max_chain >= 4 - * For deflate_fast() (levels <= 3) good is ignored and lazy has a different - * meaning. - */ - -#define EQUAL 0 -/* result of memcmp for equal strings */ - -#ifndef NO_DUMMY_DECL -struct static_tree_desc_s {int dummy;}; /* for buggy compilers */ -#endif - -/* =========================================================================== - * Update a hash value with the given input byte - * IN assertion: all calls to to UPDATE_HASH are made with consecutive - * input characters, so that a running hash key can be computed from the - * previous key instead of complete recalculation each time. - */ -#define UPDATE_HASH(s,h,c) (h = (((h)<hash_shift) ^ (c)) & s->hash_mask) - - -/* =========================================================================== - * Insert string str in the dictionary and set match_head to the previous head - * of the hash chain (the most recent string with same hash key). Return - * the previous length of the hash chain. - * If this file is compiled with -DFASTEST, the compression level is forced - * to 1, and no hash chains are maintained. - * IN assertion: all calls to to INSERT_STRING are made with consecutive - * input characters and the first MIN_MATCH bytes of str are valid - * (except for the last MIN_MATCH-1 bytes of the input file). - */ -#ifdef FASTEST -#define INSERT_STRING(s, str, match_head) \ - (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \ - match_head = s->head[s->ins_h], \ - s->head[s->ins_h] = (Pos)(str)) -#else -#define INSERT_STRING(s, str, match_head) \ - (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \ - match_head = s->prev[(str) & s->w_mask] = s->head[s->ins_h], \ - s->head[s->ins_h] = (Pos)(str)) -#endif - -/* =========================================================================== - * Initialize the hash table (avoiding 64K overflow for 16 bit systems). - * prev[] will be initialized on the fly. - */ -#define CLEAR_HASH(s) \ - s->head[s->hash_size-1] = NIL; \ - zmemzero((Bytef *)s->head, (unsigned)(s->hash_size-1)*sizeof(*s->head)); - -/* ========================================================================= */ -int ZEXPORT deflateInit_(strm, level, version, stream_size) - z_streamp strm; - int level; - const char *version; - int stream_size; -{ - return deflateInit2_(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, - Z_DEFAULT_STRATEGY, version, stream_size); - /* To do: ignore strm->next_in if we use it as window */ -} - -/* ========================================================================= */ -int ZEXPORT deflateInit2_(strm, level, method, windowBits, memLevel, strategy, - version, stream_size) - z_streamp strm; - int level; - int method; - int windowBits; - int memLevel; - int strategy; - const char *version; - int stream_size; -{ - deflate_state *s; - int wrap = 1; - static const char my_version[] = ZLIB_VERSION; - - ushf *overlay; - /* We overlay pending_buf and d_buf+l_buf. This works since the average - * output size for (length,distance) codes is <= 24 bits. - */ - - if (version == Z_NULL || version[0] != my_version[0] || - stream_size != sizeof(z_stream)) { - return Z_VERSION_ERROR; - } - if (strm == Z_NULL) return Z_STREAM_ERROR; - - strm->msg = Z_NULL; - if (strm->zalloc == (alloc_func)0) { - strm->zalloc = zcalloc; - strm->opaque = (voidpf)0; - } - if (strm->zfree == (free_func)0) strm->zfree = zcfree; - -#ifdef FASTEST - if (level != 0) level = 1; -#else - if (level == Z_DEFAULT_COMPRESSION) level = 6; -#endif - - if (windowBits < 0) { /* suppress zlib wrapper */ - wrap = 0; - windowBits = -windowBits; - } -#ifdef GZIP - else if (windowBits > 15) { - wrap = 2; /* write gzip wrapper instead */ - windowBits -= 16; - } -#endif - if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method != Z_DEFLATED || - windowBits < 8 || windowBits > 15 || level < 0 || level > 9 || - strategy < 0 || strategy > Z_FIXED) { - return Z_STREAM_ERROR; - } - if (windowBits == 8) windowBits = 9; /* until 256-byte window bug fixed */ - s = (deflate_state *) ZALLOC(strm, 1, sizeof(deflate_state)); - if (s == Z_NULL) return Z_MEM_ERROR; - strm->state = (struct internal_state FAR *)s; - s->strm = strm; - - s->wrap = wrap; - s->gzhead = Z_NULL; - s->w_bits = windowBits; - s->w_size = 1 << s->w_bits; - s->w_mask = s->w_size - 1; - - s->hash_bits = memLevel + 7; - s->hash_size = 1 << s->hash_bits; - s->hash_mask = s->hash_size - 1; - s->hash_shift = ((s->hash_bits+MIN_MATCH-1)/MIN_MATCH); - - s->window = (Bytef *) ZALLOC(strm, s->w_size, 2*sizeof(Byte)); - s->prev = (Posf *) ZALLOC(strm, s->w_size, sizeof(Pos)); - s->head = (Posf *) ZALLOC(strm, s->hash_size, sizeof(Pos)); - - s->lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */ - - overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2); - s->pending_buf = (uchf *) overlay; - s->pending_buf_size = (ulg)s->lit_bufsize * (sizeof(ush)+2L); - - if (s->window == Z_NULL || s->prev == Z_NULL || s->head == Z_NULL || - s->pending_buf == Z_NULL) { - s->status = FINISH_STATE; - strm->msg = (char*)ERR_MSG(Z_MEM_ERROR); - deflateEnd (strm); - return Z_MEM_ERROR; - } - s->d_buf = overlay + s->lit_bufsize/sizeof(ush); - s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize; - - s->level = level; - s->strategy = strategy; - s->method = (Byte)method; - - return deflateReset(strm); -} - -/* ========================================================================= */ -int ZEXPORT deflateSetDictionary (strm, dictionary, dictLength) - z_streamp strm; - const Bytef *dictionary; - uInt dictLength; -{ - deflate_state *s; - uInt length = dictLength; - uInt n; - IPos hash_head = 0; - - if (strm == Z_NULL || strm->state == Z_NULL || dictionary == Z_NULL || - strm->state->wrap == 2 || - (strm->state->wrap == 1 && strm->state->status != INIT_STATE)) - return Z_STREAM_ERROR; - - s = strm->state; - if (s->wrap) - strm->adler = adler32(strm->adler, dictionary, dictLength); - - if (length < MIN_MATCH) return Z_OK; - if (length > MAX_DIST(s)) { - length = MAX_DIST(s); - dictionary += dictLength - length; /* use the tail of the dictionary */ - } - zmemcpy(s->window, dictionary, length); - s->strstart = length; - s->block_start = (long)length; - - /* Insert all strings in the hash table (except for the last two bytes). - * s->lookahead stays null, so s->ins_h will be recomputed at the next - * call of fill_window. - */ - s->ins_h = s->window[0]; - UPDATE_HASH(s, s->ins_h, s->window[1]); - for (n = 0; n <= length - MIN_MATCH; n++) { - INSERT_STRING(s, n, hash_head); - } - if (hash_head) hash_head = 0; /* to make compiler happy */ - return Z_OK; -} - -/* ========================================================================= */ -int ZEXPORT deflateReset (strm) - z_streamp strm; -{ - deflate_state *s; - - if (strm == Z_NULL || strm->state == Z_NULL || - strm->zalloc == (alloc_func)0 || strm->zfree == (free_func)0) { - return Z_STREAM_ERROR; - } - - strm->total_in = strm->total_out = 0; - strm->msg = Z_NULL; /* use zfree if we ever allocate msg dynamically */ - strm->data_type = Z_UNKNOWN; - - s = (deflate_state *)strm->state; - s->pending = 0; - s->pending_out = s->pending_buf; - - if (s->wrap < 0) { - s->wrap = -s->wrap; /* was made negative by deflate(..., Z_FINISH); */ - } - s->status = s->wrap ? INIT_STATE : BUSY_STATE; - strm->adler = -#ifdef GZIP - s->wrap == 2 ? crc32(0L, Z_NULL, 0) : -#endif - adler32(0L, Z_NULL, 0); - s->last_flush = Z_NO_FLUSH; - - _tr_init(s); - lm_init(s); - - return Z_OK; -} - -/* ========================================================================= */ -int ZEXPORT deflateSetHeader (strm, head) - z_streamp strm; - gz_headerp head; -{ - if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; - if (strm->state->wrap != 2) return Z_STREAM_ERROR; - strm->state->gzhead = head; - return Z_OK; -} - -/* ========================================================================= */ -int ZEXPORT deflatePrime (strm, bits, value) - z_streamp strm; - int bits; - int value; -{ - if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; - strm->state->bi_valid = bits; - strm->state->bi_buf = (ush)(value & ((1 << bits) - 1)); - return Z_OK; -} - -/* ========================================================================= */ -int ZEXPORT deflateParams(strm, level, strategy) - z_streamp strm; - int level; - int strategy; -{ - deflate_state *s; - compress_func func; - int err = Z_OK; - - if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; - s = strm->state; - -#ifdef FASTEST - if (level != 0) level = 1; -#else - if (level == Z_DEFAULT_COMPRESSION) level = 6; -#endif - if (level < 0 || level > 9 || strategy < 0 || strategy > Z_FIXED) { - return Z_STREAM_ERROR; - } - func = configuration_table[s->level].func; - - if (func != configuration_table[level].func && strm->total_in != 0) { - /* Flush the last buffer: */ - err = deflate(strm, Z_PARTIAL_FLUSH); - } - if (s->level != level) { - s->level = level; - s->max_lazy_match = configuration_table[level].max_lazy; - s->good_match = configuration_table[level].good_length; - s->nice_match = configuration_table[level].nice_length; - s->max_chain_length = configuration_table[level].max_chain; - } - s->strategy = strategy; - return err; -} - -/* ========================================================================= */ -int ZEXPORT deflateTune(strm, good_length, max_lazy, nice_length, max_chain) - z_streamp strm; - int good_length; - int max_lazy; - int nice_length; - int max_chain; -{ - deflate_state *s; - - if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; - s = strm->state; - s->good_match = good_length; - s->max_lazy_match = max_lazy; - s->nice_match = nice_length; - s->max_chain_length = max_chain; - return Z_OK; -} - -/* ========================================================================= - * For the default windowBits of 15 and memLevel of 8, this function returns - * a close to exact, as well as small, upper bound on the compressed size. - * They are coded as constants here for a reason--if the #define's are - * changed, then this function needs to be changed as well. The return - * value for 15 and 8 only works for those exact settings. - * - * For any setting other than those defaults for windowBits and memLevel, - * the value returned is a conservative worst case for the maximum expansion - * resulting from using fixed blocks instead of stored blocks, which deflate - * can emit on compressed data for some combinations of the parameters. - * - * This function could be more sophisticated to provide closer upper bounds - * for every combination of windowBits and memLevel, as well as wrap. - * But even the conservative upper bound of about 14% expansion does not - * seem onerous for output buffer allocation. - */ -uLong ZEXPORT deflateBound(strm, sourceLen) - z_streamp strm; - uLong sourceLen; -{ - deflate_state *s; - uLong destLen; - - /* conservative upper bound */ - destLen = sourceLen + - ((sourceLen + 7) >> 3) + ((sourceLen + 63) >> 6) + 11; - - /* if can't get parameters, return conservative bound */ - if (strm == Z_NULL || strm->state == Z_NULL) - return destLen; - - /* if not default parameters, return conservative bound */ - s = strm->state; - if (s->w_bits != 15 || s->hash_bits != 8 + 7) - return destLen; - - /* default settings: return tight bound for that case */ - return compressBound(sourceLen); -} - -/* ========================================================================= - * Put a short in the pending buffer. The 16-bit value is put in MSB order. - * IN assertion: the stream state is correct and there is enough room in - * pending_buf. - */ -local void putShortMSB (s, b) - deflate_state *s; - uInt b; -{ - put_byte(s, (Byte)(b >> 8)); - put_byte(s, (Byte)(b & 0xff)); -} - -/* ========================================================================= - * Flush as much pending output as possible. All deflate() output goes - * through this function so some applications may wish to modify it - * to avoid allocating a large strm->next_out buffer and copying into it. - * (See also read_buf()). - */ -local void flush_pending(strm) - z_streamp strm; -{ - unsigned len = strm->state->pending; - - if (len > strm->avail_out) len = strm->avail_out; - if (len == 0) return; - - zmemcpy(strm->next_out, strm->state->pending_out, len); - strm->next_out += len; - strm->state->pending_out += len; - strm->total_out += len; - strm->avail_out -= len; - strm->state->pending -= len; - if (strm->state->pending == 0) { - strm->state->pending_out = strm->state->pending_buf; - } -} - -/* ========================================================================= */ -int ZEXPORT deflate (strm, flush) - z_streamp strm; - int flush; -{ - int old_flush; /* value of flush param for previous deflate call */ - deflate_state *s; - - if (strm == Z_NULL || strm->state == Z_NULL || - flush > Z_FINISH || flush < 0) { - return Z_STREAM_ERROR; - } - s = strm->state; - - if (strm->next_out == Z_NULL || - (strm->next_in == Z_NULL && strm->avail_in != 0) || - (s->status == FINISH_STATE && flush != Z_FINISH)) { - ERR_RETURN(strm, Z_STREAM_ERROR); - } - if (strm->avail_out == 0) ERR_RETURN(strm, Z_BUF_ERROR); - - s->strm = strm; /* just in case */ - old_flush = s->last_flush; - s->last_flush = flush; - - /* Write the header */ - if (s->status == INIT_STATE) { -#ifdef GZIP - if (s->wrap == 2) { - strm->adler = crc32(0L, Z_NULL, 0); - put_byte(s, 31); - put_byte(s, 139); - put_byte(s, 8); - if (s->gzhead == NULL) { - put_byte(s, 0); - put_byte(s, 0); - put_byte(s, 0); - put_byte(s, 0); - put_byte(s, 0); - put_byte(s, s->level == 9 ? 2 : - (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ? - 4 : 0)); - put_byte(s, OS_CODE); - s->status = BUSY_STATE; - } - else { - put_byte(s, (s->gzhead->text ? 1 : 0) + - (s->gzhead->hcrc ? 2 : 0) + - (s->gzhead->extra == Z_NULL ? 0 : 4) + - (s->gzhead->name == Z_NULL ? 0 : 8) + - (s->gzhead->comment == Z_NULL ? 0 : 16) - ); - put_byte(s, (Byte)(s->gzhead->time & 0xff)); - put_byte(s, (Byte)((s->gzhead->time >> 8) & 0xff)); - put_byte(s, (Byte)((s->gzhead->time >> 16) & 0xff)); - put_byte(s, (Byte)((s->gzhead->time >> 24) & 0xff)); - put_byte(s, s->level == 9 ? 2 : - (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ? - 4 : 0)); - put_byte(s, s->gzhead->os & 0xff); - if (s->gzhead->extra != NULL) { - put_byte(s, s->gzhead->extra_len & 0xff); - put_byte(s, (s->gzhead->extra_len >> 8) & 0xff); - } - if (s->gzhead->hcrc) - strm->adler = crc32(strm->adler, s->pending_buf, - s->pending); - s->gzindex = 0; - s->status = EXTRA_STATE; - } - } - else -#endif - { - uInt header = (Z_DEFLATED + ((s->w_bits-8)<<4)) << 8; - uInt level_flags; - - if (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2) - level_flags = 0; - else if (s->level < 6) - level_flags = 1; - else if (s->level == 6) - level_flags = 2; - else - level_flags = 3; - header |= (level_flags << 6); - if (s->strstart != 0) header |= PRESET_DICT; - header += 31 - (header % 31); - - s->status = BUSY_STATE; - putShortMSB(s, header); - - /* Save the adler32 of the preset dictionary: */ - if (s->strstart != 0) { - putShortMSB(s, (uInt)(strm->adler >> 16)); - putShortMSB(s, (uInt)(strm->adler & 0xffff)); - } - strm->adler = adler32(0L, Z_NULL, 0); - } - } -#ifdef GZIP - if (s->status == EXTRA_STATE) { - if (s->gzhead->extra != NULL) { - uInt beg = s->pending; /* start of bytes to update crc */ - - while (s->gzindex < (s->gzhead->extra_len & 0xffff)) { - if (s->pending == s->pending_buf_size) { - if (s->gzhead->hcrc && s->pending > beg) - strm->adler = crc32(strm->adler, s->pending_buf + beg, - s->pending - beg); - flush_pending(strm); - beg = s->pending; - if (s->pending == s->pending_buf_size) - break; - } - put_byte(s, s->gzhead->extra[s->gzindex]); - s->gzindex++; - } - if (s->gzhead->hcrc && s->pending > beg) - strm->adler = crc32(strm->adler, s->pending_buf + beg, - s->pending - beg); - if (s->gzindex == s->gzhead->extra_len) { - s->gzindex = 0; - s->status = NAME_STATE; - } - } - else - s->status = NAME_STATE; - } - if (s->status == NAME_STATE) { - if (s->gzhead->name != NULL) { - uInt beg = s->pending; /* start of bytes to update crc */ - int val; - - do { - if (s->pending == s->pending_buf_size) { - if (s->gzhead->hcrc && s->pending > beg) - strm->adler = crc32(strm->adler, s->pending_buf + beg, - s->pending - beg); - flush_pending(strm); - beg = s->pending; - if (s->pending == s->pending_buf_size) { - val = 1; - break; - } - } - val = s->gzhead->name[s->gzindex++]; - put_byte(s, val); - } while (val != 0); - if (s->gzhead->hcrc && s->pending > beg) - strm->adler = crc32(strm->adler, s->pending_buf + beg, - s->pending - beg); - if (val == 0) { - s->gzindex = 0; - s->status = COMMENT_STATE; - } - } - else - s->status = COMMENT_STATE; - } - if (s->status == COMMENT_STATE) { - if (s->gzhead->comment != NULL) { - uInt beg = s->pending; /* start of bytes to update crc */ - int val; - - do { - if (s->pending == s->pending_buf_size) { - if (s->gzhead->hcrc && s->pending > beg) - strm->adler = crc32(strm->adler, s->pending_buf + beg, - s->pending - beg); - flush_pending(strm); - beg = s->pending; - if (s->pending == s->pending_buf_size) { - val = 1; - break; - } - } - val = s->gzhead->comment[s->gzindex++]; - put_byte(s, val); - } while (val != 0); - if (s->gzhead->hcrc && s->pending > beg) - strm->adler = crc32(strm->adler, s->pending_buf + beg, - s->pending - beg); - if (val == 0) - s->status = HCRC_STATE; - } - else - s->status = HCRC_STATE; - } - if (s->status == HCRC_STATE) { - if (s->gzhead->hcrc) { - if (s->pending + 2 > s->pending_buf_size) - flush_pending(strm); - if (s->pending + 2 <= s->pending_buf_size) { - put_byte(s, (Byte)(strm->adler & 0xff)); - put_byte(s, (Byte)((strm->adler >> 8) & 0xff)); - strm->adler = crc32(0L, Z_NULL, 0); - s->status = BUSY_STATE; - } - } - else - s->status = BUSY_STATE; - } -#endif - - /* Flush as much pending output as possible */ - if (s->pending != 0) { - flush_pending(strm); - if (strm->avail_out == 0) { - /* Since avail_out is 0, deflate will be called again with - * more output space, but possibly with both pending and - * avail_in equal to zero. There won't be anything to do, - * but this is not an error situation so make sure we - * return OK instead of BUF_ERROR at next call of deflate: - */ - s->last_flush = -1; - return Z_OK; - } - - /* Make sure there is something to do and avoid duplicate consecutive - * flushes. For repeated and useless calls with Z_FINISH, we keep - * returning Z_STREAM_END instead of Z_BUF_ERROR. - */ - } else if (strm->avail_in == 0 && flush <= old_flush && - flush != Z_FINISH) { - ERR_RETURN(strm, Z_BUF_ERROR); - } - - /* User must not provide more input after the first FINISH: */ - if (s->status == FINISH_STATE && strm->avail_in != 0) { - ERR_RETURN(strm, Z_BUF_ERROR); - } - - /* Start a new block or continue the current one. - */ - if (strm->avail_in != 0 || s->lookahead != 0 || - (flush != Z_NO_FLUSH && s->status != FINISH_STATE)) { - block_state bstate; - - bstate = (*(configuration_table[s->level].func))(s, flush); - - if (bstate == finish_started || bstate == finish_done) { - s->status = FINISH_STATE; - } - if (bstate == need_more || bstate == finish_started) { - if (strm->avail_out == 0) { - s->last_flush = -1; /* avoid BUF_ERROR next call, see above */ - } - return Z_OK; - /* If flush != Z_NO_FLUSH && avail_out == 0, the next call - * of deflate should use the same flush parameter to make sure - * that the flush is complete. So we don't have to output an - * empty block here, this will be done at next call. This also - * ensures that for a very small output buffer, we emit at most - * one empty block. - */ - } - if (bstate == block_done) { - if (flush == Z_PARTIAL_FLUSH) { - _tr_align(s); - } else { /* FULL_FLUSH or SYNC_FLUSH */ - _tr_stored_block(s, (char*)0, 0L, 0); - /* For a full flush, this empty block will be recognized - * as a special marker by inflate_sync(). - */ - if (flush == Z_FULL_FLUSH) { - CLEAR_HASH(s); /* forget history */ - } - } - flush_pending(strm); - if (strm->avail_out == 0) { - s->last_flush = -1; /* avoid BUF_ERROR at next call, see above */ - return Z_OK; - } - } - } - Assert(strm->avail_out > 0, "bug2"); - - if (flush != Z_FINISH) return Z_OK; - if (s->wrap <= 0) return Z_STREAM_END; - - /* Write the trailer */ -#ifdef GZIP - if (s->wrap == 2) { - put_byte(s, (Byte)(strm->adler & 0xff)); - put_byte(s, (Byte)((strm->adler >> 8) & 0xff)); - put_byte(s, (Byte)((strm->adler >> 16) & 0xff)); - put_byte(s, (Byte)((strm->adler >> 24) & 0xff)); - put_byte(s, (Byte)(strm->total_in & 0xff)); - put_byte(s, (Byte)((strm->total_in >> 8) & 0xff)); - put_byte(s, (Byte)((strm->total_in >> 16) & 0xff)); - put_byte(s, (Byte)((strm->total_in >> 24) & 0xff)); - } - else -#endif - { - putShortMSB(s, (uInt)(strm->adler >> 16)); - putShortMSB(s, (uInt)(strm->adler & 0xffff)); - } - flush_pending(strm); - /* If avail_out is zero, the application will call deflate again - * to flush the rest. - */ - if (s->wrap > 0) s->wrap = -s->wrap; /* write the trailer only once! */ - return s->pending != 0 ? Z_OK : Z_STREAM_END; -} - -/* ========================================================================= */ -int ZEXPORT deflateEnd (strm) - z_streamp strm; -{ - int status; - - if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; - - status = strm->state->status; - if (status != INIT_STATE && - status != EXTRA_STATE && - status != NAME_STATE && - status != COMMENT_STATE && - status != HCRC_STATE && - status != BUSY_STATE && - status != FINISH_STATE) { - return Z_STREAM_ERROR; - } - - /* Deallocate in reverse order of allocations: */ - TRY_FREE(strm, strm->state->pending_buf); - TRY_FREE(strm, strm->state->head); - TRY_FREE(strm, strm->state->prev); - TRY_FREE(strm, strm->state->window); - - ZFREE(strm, strm->state); - strm->state = Z_NULL; - - return status == BUSY_STATE ? Z_DATA_ERROR : Z_OK; -} - -/* ========================================================================= - * Copy the source state to the destination state. - * To simplify the source, this is not supported for 16-bit MSDOS (which - * doesn't have enough memory anyway to duplicate compression states). - */ -int ZEXPORT deflateCopy (dest, source) - z_streamp dest; - z_streamp source; -{ -#ifdef MAXSEG_64K - return Z_STREAM_ERROR; -#else - deflate_state *ds; - deflate_state *ss; - ushf *overlay; - - - if (source == Z_NULL || dest == Z_NULL || source->state == Z_NULL) { - return Z_STREAM_ERROR; - } - - ss = source->state; - - zmemcpy(dest, source, sizeof(z_stream)); - - ds = (deflate_state *) ZALLOC(dest, 1, sizeof(deflate_state)); - if (ds == Z_NULL) return Z_MEM_ERROR; - dest->state = (struct internal_state FAR *) ds; - zmemcpy(ds, ss, sizeof(deflate_state)); - ds->strm = dest; - - ds->window = (Bytef *) ZALLOC(dest, ds->w_size, 2*sizeof(Byte)); - ds->prev = (Posf *) ZALLOC(dest, ds->w_size, sizeof(Pos)); - ds->head = (Posf *) ZALLOC(dest, ds->hash_size, sizeof(Pos)); - overlay = (ushf *) ZALLOC(dest, ds->lit_bufsize, sizeof(ush)+2); - ds->pending_buf = (uchf *) overlay; - - if (ds->window == Z_NULL || ds->prev == Z_NULL || ds->head == Z_NULL || - ds->pending_buf == Z_NULL) { - deflateEnd (dest); - return Z_MEM_ERROR; - } - /* following zmemcpy do not work for 16-bit MSDOS */ - zmemcpy(ds->window, ss->window, ds->w_size * 2 * sizeof(Byte)); - zmemcpy(ds->prev, ss->prev, ds->w_size * sizeof(Pos)); - zmemcpy(ds->head, ss->head, ds->hash_size * sizeof(Pos)); - zmemcpy(ds->pending_buf, ss->pending_buf, (uInt)ds->pending_buf_size); - - ds->pending_out = ds->pending_buf + (ss->pending_out - ss->pending_buf); - ds->d_buf = overlay + ds->lit_bufsize/sizeof(ush); - ds->l_buf = ds->pending_buf + (1+sizeof(ush))*ds->lit_bufsize; - - ds->l_desc.dyn_tree = ds->dyn_ltree; - ds->d_desc.dyn_tree = ds->dyn_dtree; - ds->bl_desc.dyn_tree = ds->bl_tree; - - return Z_OK; -#endif /* MAXSEG_64K */ -} - -/* =========================================================================== - * Read a new buffer from the current input stream, update the adler32 - * and total number of bytes read. All deflate() input goes through - * this function so some applications may wish to modify it to avoid - * allocating a large strm->next_in buffer and copying from it. - * (See also flush_pending()). - */ -local int read_buf(strm, buf, size) - z_streamp strm; - Bytef *buf; - unsigned size; -{ - unsigned len = strm->avail_in; - - if (len > size) len = size; - if (len == 0) return 0; - - strm->avail_in -= len; - - if (strm->state->wrap == 1) { - strm->adler = adler32(strm->adler, strm->next_in, len); - } -#ifdef GZIP - else if (strm->state->wrap == 2) { - strm->adler = crc32(strm->adler, strm->next_in, len); - } -#endif - zmemcpy(buf, strm->next_in, len); - strm->next_in += len; - strm->total_in += len; - - return (int)len; -} - -/* =========================================================================== - * Initialize the "longest match" routines for a new zlib stream - */ -local void lm_init (s) - deflate_state *s; -{ - s->window_size = (ulg)2L*s->w_size; - - CLEAR_HASH(s); - - /* Set the default configuration parameters: - */ - s->max_lazy_match = configuration_table[s->level].max_lazy; - s->good_match = configuration_table[s->level].good_length; - s->nice_match = configuration_table[s->level].nice_length; - s->max_chain_length = configuration_table[s->level].max_chain; - - s->strstart = 0; - s->block_start = 0L; - s->lookahead = 0; - s->match_length = s->prev_length = MIN_MATCH-1; - s->match_available = 0; - s->ins_h = 0; -#ifndef FASTEST -#ifdef ASMV - match_init(); /* initialize the asm code */ -#endif -#endif -} - -#ifndef FASTEST -/* =========================================================================== - * Set match_start to the longest match starting at the given string and - * return its length. Matches shorter or equal to prev_length are discarded, - * in which case the result is equal to prev_length and match_start is - * garbage. - * IN assertions: cur_match is the head of the hash chain for the current - * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1 - * OUT assertion: the match length is not greater than s->lookahead. - */ -#ifndef ASMV -/* For 80x86 and 680x0, an optimized version will be provided in match.asm or - * match.S. The code will be functionally equivalent. - */ -local uInt longest_match(s, cur_match) - deflate_state *s; - IPos cur_match; /* current match */ -{ - unsigned chain_length = s->max_chain_length;/* max hash chain length */ - register Bytef *scan = s->window + s->strstart; /* current string */ - register Bytef *match; /* matched string */ - register int len; /* length of current match */ - int best_len = s->prev_length; /* best match length so far */ - int nice_match = s->nice_match; /* stop if match long enough */ - IPos limit = s->strstart > (IPos)MAX_DIST(s) ? - s->strstart - (IPos)MAX_DIST(s) : NIL; - /* Stop when cur_match becomes <= limit. To simplify the code, - * we prevent matches with the string of window index 0. - */ - Posf *prev = s->prev; - uInt wmask = s->w_mask; - -#ifdef UNALIGNED_OK - /* Compare two bytes at a time. Note: this is not always beneficial. - * Try with and without -DUNALIGNED_OK to check. - */ - register Bytef *strend = s->window + s->strstart + MAX_MATCH - 1; - register ush scan_start = *(ushf*)scan; - register ush scan_end = *(ushf*)(scan+best_len-1); -#else - register Bytef *strend = s->window + s->strstart + MAX_MATCH; - register Byte scan_end1 = scan[best_len-1]; - register Byte scan_end = scan[best_len]; -#endif - - /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16. - * It is easy to get rid of this optimization if necessary. - */ - Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever"); - - /* Do not waste too much time if we already have a good match: */ - if (s->prev_length >= s->good_match) { - chain_length >>= 2; - } - /* Do not look for matches beyond the end of the input. This is necessary - * to make deflate deterministic. - */ - if ((uInt)nice_match > s->lookahead) nice_match = s->lookahead; - - Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead"); - - do { - Assert(cur_match < s->strstart, "no future"); - match = s->window + cur_match; - - /* Skip to next match if the match length cannot increase - * or if the match length is less than 2. Note that the checks below - * for insufficient lookahead only occur occasionally for performance - * reasons. Therefore uninitialized memory will be accessed, and - * conditional jumps will be made that depend on those values. - * However the length of the match is limited to the lookahead, so - * the output of deflate is not affected by the uninitialized values. - */ -#if (defined(UNALIGNED_OK) && MAX_MATCH == 258) - /* This code assumes sizeof(unsigned short) == 2. Do not use - * UNALIGNED_OK if your compiler uses a different size. - */ - if (*(ushf*)(match+best_len-1) != scan_end || - *(ushf*)match != scan_start) continue; - - /* It is not necessary to compare scan[2] and match[2] since they are - * always equal when the other bytes match, given that the hash keys - * are equal and that HASH_BITS >= 8. Compare 2 bytes at a time at - * strstart+3, +5, ... up to strstart+257. We check for insufficient - * lookahead only every 4th comparison; the 128th check will be made - * at strstart+257. If MAX_MATCH-2 is not a multiple of 8, it is - * necessary to put more guard bytes at the end of the window, or - * to check more often for insufficient lookahead. - */ - Assert(scan[2] == match[2], "scan[2]?"); - scan++, match++; - do { - } while (*(ushf*)(scan+=2) == *(ushf*)(match+=2) && - *(ushf*)(scan+=2) == *(ushf*)(match+=2) && - *(ushf*)(scan+=2) == *(ushf*)(match+=2) && - *(ushf*)(scan+=2) == *(ushf*)(match+=2) && - scan < strend); - /* The funny "do {}" generates better code on most compilers */ - - /* Here, scan <= window+strstart+257 */ - Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan"); - if (*scan == *match) scan++; - - len = (MAX_MATCH - 1) - (int)(strend-scan); - scan = strend - (MAX_MATCH-1); - -#else /* UNALIGNED_OK */ - - if (match[best_len] != scan_end || - match[best_len-1] != scan_end1 || - *match != *scan || - *++match != scan[1]) continue; - - /* The check at best_len-1 can be removed because it will be made - * again later. (This heuristic is not always a win.) - * It is not necessary to compare scan[2] and match[2] since they - * are always equal when the other bytes match, given that - * the hash keys are equal and that HASH_BITS >= 8. - */ - scan += 2, match++; - Assert(*scan == *match, "match[2]?"); - - /* We check for insufficient lookahead only every 8th comparison; - * the 256th check will be made at strstart+258. - */ - do { - } while (*++scan == *++match && *++scan == *++match && - *++scan == *++match && *++scan == *++match && - *++scan == *++match && *++scan == *++match && - *++scan == *++match && *++scan == *++match && - scan < strend); - - Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan"); - - len = MAX_MATCH - (int)(strend - scan); - scan = strend - MAX_MATCH; - -#endif /* UNALIGNED_OK */ - - if (len > best_len) { - s->match_start = cur_match; - best_len = len; - if (len >= nice_match) break; -#ifdef UNALIGNED_OK - scan_end = *(ushf*)(scan+best_len-1); -#else - scan_end1 = scan[best_len-1]; - scan_end = scan[best_len]; -#endif - } - } while ((cur_match = prev[cur_match & wmask]) > limit - && --chain_length != 0); - - if ((uInt)best_len <= s->lookahead) return (uInt)best_len; - return s->lookahead; -} -#endif /* ASMV */ -#endif /* FASTEST */ - -/* --------------------------------------------------------------------------- - * Optimized version for level == 1 or strategy == Z_RLE only - */ -local uInt longest_match_fast(s, cur_match) - deflate_state *s; - IPos cur_match; /* current match */ -{ - register Bytef *scan = s->window + s->strstart; /* current string */ - register Bytef *match; /* matched string */ - register int len; /* length of current match */ - register Bytef *strend = s->window + s->strstart + MAX_MATCH; - - /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16. - * It is easy to get rid of this optimization if necessary. - */ - Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever"); - - Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead"); - - Assert(cur_match < s->strstart, "no future"); - - match = s->window + cur_match; - - /* Return failure if the match length is less than 2: - */ - if (match[0] != scan[0] || match[1] != scan[1]) return MIN_MATCH-1; - - /* The check at best_len-1 can be removed because it will be made - * again later. (This heuristic is not always a win.) - * It is not necessary to compare scan[2] and match[2] since they - * are always equal when the other bytes match, given that - * the hash keys are equal and that HASH_BITS >= 8. - */ - scan += 2, match += 2; - Assert(*scan == *match, "match[2]?"); - - /* We check for insufficient lookahead only every 8th comparison; - * the 256th check will be made at strstart+258. - */ - do { - } while (*++scan == *++match && *++scan == *++match && - *++scan == *++match && *++scan == *++match && - *++scan == *++match && *++scan == *++match && - *++scan == *++match && *++scan == *++match && - scan < strend); - - Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan"); - - len = MAX_MATCH - (int)(strend - scan); - - if (len < MIN_MATCH) return MIN_MATCH - 1; - - s->match_start = cur_match; - return (uInt)len <= s->lookahead ? (uInt)len : s->lookahead; -} - -#ifdef DEBUG -/* =========================================================================== - * Check that the match at match_start is indeed a match. - */ -local void check_match(s, start, match, length) - deflate_state *s; - IPos start, match; - int length; -{ - /* check that the match is indeed a match */ - if (zmemcmp(s->window + match, - s->window + start, length) != EQUAL) { - fprintf(stderr, " start %u, match %u, length %d\n", - start, match, length); - do { - fprintf(stderr, "%c%c", s->window[match++], s->window[start++]); - } while (--length != 0); - z_error("invalid match"); - } - if (z_verbose > 1) { - fprintf(stderr,"\\[%d,%d]", start-match, length); - do { putc(s->window[start++], stderr); } while (--length != 0); - } -} -#else -# define check_match(s, start, match, length) -#endif /* DEBUG */ - -/* =========================================================================== - * Fill the window when the lookahead becomes insufficient. - * Updates strstart and lookahead. - * - * IN assertion: lookahead < MIN_LOOKAHEAD - * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD - * At least one byte has been read, or avail_in == 0; reads are - * performed for at least two bytes (required for the zip translate_eol - * option -- not supported here). - */ -local void fill_window(s) - deflate_state *s; -{ - register unsigned n, m; - register Posf *p; - unsigned more; /* Amount of free space at the end of the window. */ - uInt wsize = s->w_size; - - do { - more = (unsigned)(s->window_size -(ulg)s->lookahead -(ulg)s->strstart); - - /* Deal with !@#$% 64K limit: */ - if (sizeof(int) <= 2) { - if (more == 0 && s->strstart == 0 && s->lookahead == 0) { - more = wsize; - - } else if (more == (unsigned)(-1)) { - /* Very unlikely, but possible on 16 bit machine if - * strstart == 0 && lookahead == 1 (input done a byte at time) - */ - more--; - } - } - - /* If the window is almost full and there is insufficient lookahead, - * move the upper half to the lower one to make room in the upper half. - */ - if (s->strstart >= wsize+MAX_DIST(s)) { - - zmemcpy(s->window, s->window+wsize, (unsigned)wsize); - s->match_start -= wsize; - s->strstart -= wsize; /* we now have strstart >= MAX_DIST */ - s->block_start -= (long) wsize; - - /* Slide the hash table (could be avoided with 32 bit values - at the expense of memory usage). We slide even when level == 0 - to keep the hash table consistent if we switch back to level > 0 - later. (Using level 0 permanently is not an optimal usage of - zlib, so we don't care about this pathological case.) - */ - /* %%% avoid this when Z_RLE */ - n = s->hash_size; - p = &s->head[n]; - do { - m = *--p; - *p = (Pos)(m >= wsize ? m-wsize : NIL); - } while (--n); - - n = wsize; -#ifndef FASTEST - p = &s->prev[n]; - do { - m = *--p; - *p = (Pos)(m >= wsize ? m-wsize : NIL); - /* If n is not on any hash chain, prev[n] is garbage but - * its value will never be used. - */ - } while (--n); -#endif - more += wsize; - } - if (s->strm->avail_in == 0) return; - - /* If there was no sliding: - * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 && - * more == window_size - lookahead - strstart - * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1) - * => more >= window_size - 2*WSIZE + 2 - * In the BIG_MEM or MMAP case (not yet supported), - * window_size == input_size + MIN_LOOKAHEAD && - * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD. - * Otherwise, window_size == 2*WSIZE so more >= 2. - * If there was sliding, more >= WSIZE. So in all cases, more >= 2. - */ - Assert(more >= 2, "more < 2"); - - n = read_buf(s->strm, s->window + s->strstart + s->lookahead, more); - s->lookahead += n; - - /* Initialize the hash value now that we have some input: */ - if (s->lookahead >= MIN_MATCH) { - s->ins_h = s->window[s->strstart]; - UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]); -#if MIN_MATCH != 3 - Call UPDATE_HASH() MIN_MATCH-3 more times -#endif - } - /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage, - * but this is not important since only literal bytes will be emitted. - */ - - } while (s->lookahead < MIN_LOOKAHEAD && s->strm->avail_in != 0); -} - -/* =========================================================================== - * Flush the current block, with given end-of-file flag. - * IN assertion: strstart is set to the end of the current match. - */ -#define FLUSH_BLOCK_ONLY(s, eof) { \ - _tr_flush_block(s, (s->block_start >= 0L ? \ - (charf *)&s->window[(unsigned)s->block_start] : \ - (charf *)Z_NULL), \ - (ulg)((long)s->strstart - s->block_start), \ - (eof)); \ - s->block_start = s->strstart; \ - flush_pending(s->strm); \ - Tracev((stderr,"[FLUSH]")); \ -} - -/* Same but force premature exit if necessary. */ -#define FLUSH_BLOCK(s, eof) { \ - FLUSH_BLOCK_ONLY(s, eof); \ - if (s->strm->avail_out == 0) return (eof) ? finish_started : need_more; \ -} - -/* =========================================================================== - * Copy without compression as much as possible from the input stream, return - * the current block state. - * This function does not insert new strings in the dictionary since - * uncompressible data is probably not useful. This function is used - * only for the level=0 compression option. - * NOTE: this function should be optimized to avoid extra copying from - * window to pending_buf. - */ -local block_state deflate_stored(s, flush) - deflate_state *s; - int flush; -{ - /* Stored blocks are limited to 0xffff bytes, pending_buf is limited - * to pending_buf_size, and each stored block has a 5 byte header: - */ - ulg max_block_size = 0xffff; - ulg max_start; - - if (max_block_size > s->pending_buf_size - 5) { - max_block_size = s->pending_buf_size - 5; - } - - /* Copy as much as possible from input to output: */ - for (;;) { - /* Fill the window as much as possible: */ - if (s->lookahead <= 1) { - - Assert(s->strstart < s->w_size+MAX_DIST(s) || - s->block_start >= (long)s->w_size, "slide too late"); - - fill_window(s); - if (s->lookahead == 0 && flush == Z_NO_FLUSH) return need_more; - - if (s->lookahead == 0) break; /* flush the current block */ - } - Assert(s->block_start >= 0L, "block gone"); - - s->strstart += s->lookahead; - s->lookahead = 0; - - /* Emit a stored block if pending_buf will be full: */ - max_start = s->block_start + max_block_size; - if (s->strstart == 0 || (ulg)s->strstart >= max_start) { - /* strstart == 0 is possible when wraparound on 16-bit machine */ - s->lookahead = (uInt)(s->strstart - max_start); - s->strstart = (uInt)max_start; - FLUSH_BLOCK(s, 0); - } - /* Flush if we may have to slide, otherwise block_start may become - * negative and the data will be gone: - */ - if (s->strstart - (uInt)s->block_start >= MAX_DIST(s)) { - FLUSH_BLOCK(s, 0); - } - } - FLUSH_BLOCK(s, flush == Z_FINISH); - return flush == Z_FINISH ? finish_done : block_done; -} - -/* =========================================================================== - * Compress as much as possible from the input stream, return the current - * block state. - * This function does not perform lazy evaluation of matches and inserts - * new strings in the dictionary only for unmatched strings or for short - * matches. It is used only for the fast compression options. - */ -local block_state deflate_fast(s, flush) - deflate_state *s; - int flush; -{ - IPos hash_head = NIL; /* head of the hash chain */ - int bflush; /* set if current block must be flushed */ - - for (;;) { - /* Make sure that we always have enough lookahead, except - * at the end of the input file. We need MAX_MATCH bytes - * for the next match, plus MIN_MATCH bytes to insert the - * string following the next match. - */ - if (s->lookahead < MIN_LOOKAHEAD) { - fill_window(s); - if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) { - return need_more; - } - if (s->lookahead == 0) break; /* flush the current block */ - } - - /* Insert the string window[strstart .. strstart+2] in the - * dictionary, and set hash_head to the head of the hash chain: - */ - if (s->lookahead >= MIN_MATCH) { - INSERT_STRING(s, s->strstart, hash_head); - } - - /* Find the longest match, discarding those <= prev_length. - * At this point we have always match_length < MIN_MATCH - */ - if (hash_head != NIL && s->strstart - hash_head <= MAX_DIST(s)) { - /* To simplify the code, we prevent matches with the string - * of window index 0 (in particular we have to avoid a match - * of the string with itself at the start of the input file). - */ -#ifdef FASTEST - if ((s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) || - (s->strategy == Z_RLE && s->strstart - hash_head == 1)) { - s->match_length = longest_match_fast (s, hash_head); - } -#else - if (s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) { - s->match_length = longest_match (s, hash_head); - } else if (s->strategy == Z_RLE && s->strstart - hash_head == 1) { - s->match_length = longest_match_fast (s, hash_head); - } -#endif - /* longest_match() or longest_match_fast() sets match_start */ - } - if (s->match_length >= MIN_MATCH) { - check_match(s, s->strstart, s->match_start, s->match_length); - - _tr_tally_dist(s, s->strstart - s->match_start, - s->match_length - MIN_MATCH, bflush); - - s->lookahead -= s->match_length; - - /* Insert new strings in the hash table only if the match length - * is not too large. This saves time but degrades compression. - */ -#ifndef FASTEST - if (s->match_length <= s->max_insert_length && - s->lookahead >= MIN_MATCH) { - s->match_length--; /* string at strstart already in table */ - do { - s->strstart++; - INSERT_STRING(s, s->strstart, hash_head); - /* strstart never exceeds WSIZE-MAX_MATCH, so there are - * always MIN_MATCH bytes ahead. - */ - } while (--s->match_length != 0); - s->strstart++; - } else -#endif - { - s->strstart += s->match_length; - s->match_length = 0; - s->ins_h = s->window[s->strstart]; - UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]); -#if MIN_MATCH != 3 - Call UPDATE_HASH() MIN_MATCH-3 more times -#endif - /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not - * matter since it will be recomputed at next deflate call. - */ - } - } else { - /* No match, output a literal byte */ - Tracevv((stderr,"%c", s->window[s->strstart])); - _tr_tally_lit (s, s->window[s->strstart], bflush); - s->lookahead--; - s->strstart++; - } - if (bflush) FLUSH_BLOCK(s, 0); - } - FLUSH_BLOCK(s, flush == Z_FINISH); - return flush == Z_FINISH ? finish_done : block_done; -} - -#ifndef FASTEST -/* =========================================================================== - * Same as above, but achieves better compression. We use a lazy - * evaluation for matches: a match is finally adopted only if there is - * no better match at the next window position. - */ -local block_state deflate_slow(s, flush) - deflate_state *s; - int flush; -{ - IPos hash_head = NIL; /* head of hash chain */ - int bflush; /* set if current block must be flushed */ - - /* Process the input block. */ - for (;;) { - /* Make sure that we always have enough lookahead, except - * at the end of the input file. We need MAX_MATCH bytes - * for the next match, plus MIN_MATCH bytes to insert the - * string following the next match. - */ - if (s->lookahead < MIN_LOOKAHEAD) { - fill_window(s); - if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) { - return need_more; - } - if (s->lookahead == 0) break; /* flush the current block */ - } - - /* Insert the string window[strstart .. strstart+2] in the - * dictionary, and set hash_head to the head of the hash chain: - */ - if (s->lookahead >= MIN_MATCH) { - INSERT_STRING(s, s->strstart, hash_head); - } - - /* Find the longest match, discarding those <= prev_length. - */ - s->prev_length = s->match_length, s->prev_match = s->match_start; - s->match_length = MIN_MATCH-1; - - if (hash_head != NIL && s->prev_length < s->max_lazy_match && - s->strstart - hash_head <= MAX_DIST(s)) { - /* To simplify the code, we prevent matches with the string - * of window index 0 (in particular we have to avoid a match - * of the string with itself at the start of the input file). - */ - if (s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) { - s->match_length = longest_match (s, hash_head); - } else if (s->strategy == Z_RLE && s->strstart - hash_head == 1) { - s->match_length = longest_match_fast (s, hash_head); - } - /* longest_match() or longest_match_fast() sets match_start */ - - if (s->match_length <= 5 && (s->strategy == Z_FILTERED -#if TOO_FAR <= 32767 - || (s->match_length == MIN_MATCH && - s->strstart - s->match_start > TOO_FAR) -#endif - )) { - - /* If prev_match is also MIN_MATCH, match_start is garbage - * but we will ignore the current match anyway. - */ - s->match_length = MIN_MATCH-1; - } - } - /* If there was a match at the previous step and the current - * match is not better, output the previous match: - */ - if (s->prev_length >= MIN_MATCH && s->match_length <= s->prev_length) { - uInt max_insert = s->strstart + s->lookahead - MIN_MATCH; - /* Do not insert strings in hash table beyond this. */ - - check_match(s, s->strstart-1, s->prev_match, s->prev_length); - - _tr_tally_dist(s, s->strstart -1 - s->prev_match, - s->prev_length - MIN_MATCH, bflush); - - /* Insert in hash table all strings up to the end of the match. - * strstart-1 and strstart are already inserted. If there is not - * enough lookahead, the last two strings are not inserted in - * the hash table. - */ - s->lookahead -= s->prev_length-1; - s->prev_length -= 2; - do { - if (++s->strstart <= max_insert) { - INSERT_STRING(s, s->strstart, hash_head); - } - } while (--s->prev_length != 0); - s->match_available = 0; - s->match_length = MIN_MATCH-1; - s->strstart++; - - if (bflush) FLUSH_BLOCK(s, 0); - - } else if (s->match_available) { - /* If there was no match at the previous position, output a - * single literal. If there was a match but the current match - * is longer, truncate the previous match to a single literal. - */ - Tracevv((stderr,"%c", s->window[s->strstart-1])); - _tr_tally_lit(s, s->window[s->strstart-1], bflush); - if (bflush) { - FLUSH_BLOCK_ONLY(s, 0); - } - s->strstart++; - s->lookahead--; - if (s->strm->avail_out == 0) return need_more; - } else { - /* There is no previous match to compare with, wait for - * the next step to decide. - */ - s->match_available = 1; - s->strstart++; - s->lookahead--; - } - } - Assert (flush != Z_NO_FLUSH, "no flush?"); - if (s->match_available) { - Tracevv((stderr,"%c", s->window[s->strstart-1])); - _tr_tally_lit(s, s->window[s->strstart-1], bflush); - s->match_available = 0; - } - FLUSH_BLOCK(s, flush == Z_FINISH); - return flush == Z_FINISH ? finish_done : block_done; -} -#endif /* FASTEST */ - -#if 0 -/* =========================================================================== - * For Z_RLE, simply look for runs of bytes, generate matches only of distance - * one. Do not maintain a hash table. (It will be regenerated if this run of - * deflate switches away from Z_RLE.) - */ -local block_state deflate_rle(s, flush) - deflate_state *s; - int flush; -{ - int bflush; /* set if current block must be flushed */ - uInt run; /* length of run */ - uInt max; /* maximum length of run */ - uInt prev; /* byte at distance one to match */ - Bytef *scan; /* scan for end of run */ - - for (;;) { - /* Make sure that we always have enough lookahead, except - * at the end of the input file. We need MAX_MATCH bytes - * for the longest encodable run. - */ - if (s->lookahead < MAX_MATCH) { - fill_window(s); - if (s->lookahead < MAX_MATCH && flush == Z_NO_FLUSH) { - return need_more; - } - if (s->lookahead == 0) break; /* flush the current block */ - } - - /* See how many times the previous byte repeats */ - run = 0; - if (s->strstart > 0) { /* if there is a previous byte, that is */ - max = s->lookahead < MAX_MATCH ? s->lookahead : MAX_MATCH; - scan = s->window + s->strstart - 1; - prev = *scan++; - do { - if (*scan++ != prev) - break; - } while (++run < max); - } - - /* Emit match if have run of MIN_MATCH or longer, else emit literal */ - if (run >= MIN_MATCH) { - check_match(s, s->strstart, s->strstart - 1, run); - _tr_tally_dist(s, 1, run - MIN_MATCH, bflush); - s->lookahead -= run; - s->strstart += run; - } else { - /* No match, output a literal byte */ - Tracevv((stderr,"%c", s->window[s->strstart])); - _tr_tally_lit (s, s->window[s->strstart], bflush); - s->lookahead--; - s->strstart++; - } - if (bflush) FLUSH_BLOCK(s, 0); - } - FLUSH_BLOCK(s, flush == Z_FINISH); - return flush == Z_FINISH ? finish_done : block_done; -} -#endif diff --git a/sourcepawn/third_party/zlib/deflate.h b/sourcepawn/third_party/zlib/deflate.h deleted file mode 100644 index 222c53e0..00000000 --- a/sourcepawn/third_party/zlib/deflate.h +++ /dev/null @@ -1,331 +0,0 @@ -/* deflate.h -- internal compression state - * Copyright (C) 1995-2004 Jean-loup Gailly - * For conditions of distribution and use, see copyright notice in zlib.h - */ - -/* WARNING: this file should *not* be used by applications. It is - part of the implementation of the compression library and is - subject to change. Applications should only use zlib.h. - */ - -/* @(#) $Id$ */ - -#ifndef DEFLATE_H -#define DEFLATE_H - -#include "zutil.h" - -/* define NO_GZIP when compiling if you want to disable gzip header and - trailer creation by deflate(). NO_GZIP would be used to avoid linking in - the crc code when it is not needed. For shared libraries, gzip encoding - should be left enabled. */ -#ifndef NO_GZIP -# define GZIP -#endif - -/* =========================================================================== - * Internal compression state. - */ - -#define LENGTH_CODES 29 -/* number of length codes, not counting the special END_BLOCK code */ - -#define LITERALS 256 -/* number of literal bytes 0..255 */ - -#define L_CODES (LITERALS+1+LENGTH_CODES) -/* number of Literal or Length codes, including the END_BLOCK code */ - -#define D_CODES 30 -/* number of distance codes */ - -#define BL_CODES 19 -/* number of codes used to transfer the bit lengths */ - -#define HEAP_SIZE (2*L_CODES+1) -/* maximum heap size */ - -#define MAX_BITS 15 -/* All codes must not exceed MAX_BITS bits */ - -#define INIT_STATE 42 -#define EXTRA_STATE 69 -#define NAME_STATE 73 -#define COMMENT_STATE 91 -#define HCRC_STATE 103 -#define BUSY_STATE 113 -#define FINISH_STATE 666 -/* Stream status */ - - -/* Data structure describing a single value and its code string. */ -typedef struct ct_data_s { - union { - ush freq; /* frequency count */ - ush code; /* bit string */ - } fc; - union { - ush dad; /* father node in Huffman tree */ - ush len; /* length of bit string */ - } dl; -} FAR ct_data; - -#define Freq fc.freq -#define Code fc.code -#define Dad dl.dad -#define Len dl.len - -typedef struct static_tree_desc_s static_tree_desc; - -typedef struct tree_desc_s { - ct_data *dyn_tree; /* the dynamic tree */ - int max_code; /* largest code with non zero frequency */ - static_tree_desc *stat_desc; /* the corresponding static tree */ -} FAR tree_desc; - -typedef ush Pos; -typedef Pos FAR Posf; -typedef unsigned IPos; - -/* A Pos is an index in the character window. We use short instead of int to - * save space in the various tables. IPos is used only for parameter passing. - */ - -typedef struct internal_state { - z_streamp strm; /* pointer back to this zlib stream */ - int status; /* as the name implies */ - Bytef *pending_buf; /* output still pending */ - ulg pending_buf_size; /* size of pending_buf */ - Bytef *pending_out; /* next pending byte to output to the stream */ - uInt pending; /* nb of bytes in the pending buffer */ - int wrap; /* bit 0 true for zlib, bit 1 true for gzip */ - gz_headerp gzhead; /* gzip header information to write */ - uInt gzindex; /* where in extra, name, or comment */ - Byte method; /* STORED (for zip only) or DEFLATED */ - int last_flush; /* value of flush param for previous deflate call */ - - /* used by deflate.c: */ - - uInt w_size; /* LZ77 window size (32K by default) */ - uInt w_bits; /* log2(w_size) (8..16) */ - uInt w_mask; /* w_size - 1 */ - - Bytef *window; - /* Sliding window. Input bytes are read into the second half of the window, - * and move to the first half later to keep a dictionary of at least wSize - * bytes. With this organization, matches are limited to a distance of - * wSize-MAX_MATCH bytes, but this ensures that IO is always - * performed with a length multiple of the block size. Also, it limits - * the window size to 64K, which is quite useful on MSDOS. - * To do: use the user input buffer as sliding window. - */ - - ulg window_size; - /* Actual size of window: 2*wSize, except when the user input buffer - * is directly used as sliding window. - */ - - Posf *prev; - /* Link to older string with same hash index. To limit the size of this - * array to 64K, this link is maintained only for the last 32K strings. - * An index in this array is thus a window index modulo 32K. - */ - - Posf *head; /* Heads of the hash chains or NIL. */ - - uInt ins_h; /* hash index of string to be inserted */ - uInt hash_size; /* number of elements in hash table */ - uInt hash_bits; /* log2(hash_size) */ - uInt hash_mask; /* hash_size-1 */ - - uInt hash_shift; - /* Number of bits by which ins_h must be shifted at each input - * step. It must be such that after MIN_MATCH steps, the oldest - * byte no longer takes part in the hash key, that is: - * hash_shift * MIN_MATCH >= hash_bits - */ - - long block_start; - /* Window position at the beginning of the current output block. Gets - * negative when the window is moved backwards. - */ - - uInt match_length; /* length of best match */ - IPos prev_match; /* previous match */ - int match_available; /* set if previous match exists */ - uInt strstart; /* start of string to insert */ - uInt match_start; /* start of matching string */ - uInt lookahead; /* number of valid bytes ahead in window */ - - uInt prev_length; - /* Length of the best match at previous step. Matches not greater than this - * are discarded. This is used in the lazy match evaluation. - */ - - uInt max_chain_length; - /* To speed up deflation, hash chains are never searched beyond this - * length. A higher limit improves compression ratio but degrades the - * speed. - */ - - uInt max_lazy_match; - /* Attempt to find a better match only when the current match is strictly - * smaller than this value. This mechanism is used only for compression - * levels >= 4. - */ -# define max_insert_length max_lazy_match - /* Insert new strings in the hash table only if the match length is not - * greater than this length. This saves time but degrades compression. - * max_insert_length is used only for compression levels <= 3. - */ - - int level; /* compression level (1..9) */ - int strategy; /* favor or force Huffman coding*/ - - uInt good_match; - /* Use a faster search when the previous match is longer than this */ - - int nice_match; /* Stop searching when current match exceeds this */ - - /* used by trees.c: */ - /* Didn't use ct_data typedef below to supress compiler warning */ - struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */ - struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */ - struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */ - - struct tree_desc_s l_desc; /* desc. for literal tree */ - struct tree_desc_s d_desc; /* desc. for distance tree */ - struct tree_desc_s bl_desc; /* desc. for bit length tree */ - - ush bl_count[MAX_BITS+1]; - /* number of codes at each bit length for an optimal tree */ - - int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */ - int heap_len; /* number of elements in the heap */ - int heap_max; /* element of largest frequency */ - /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used. - * The same heap array is used to build all trees. - */ - - uch depth[2*L_CODES+1]; - /* Depth of each subtree used as tie breaker for trees of equal frequency - */ - - uchf *l_buf; /* buffer for literals or lengths */ - - uInt lit_bufsize; - /* Size of match buffer for literals/lengths. There are 4 reasons for - * limiting lit_bufsize to 64K: - * - frequencies can be kept in 16 bit counters - * - if compression is not successful for the first block, all input - * data is still in the window so we can still emit a stored block even - * when input comes from standard input. (This can also be done for - * all blocks if lit_bufsize is not greater than 32K.) - * - if compression is not successful for a file smaller than 64K, we can - * even emit a stored file instead of a stored block (saving 5 bytes). - * This is applicable only for zip (not gzip or zlib). - * - creating new Huffman trees less frequently may not provide fast - * adaptation to changes in the input data statistics. (Take for - * example a binary file with poorly compressible code followed by - * a highly compressible string table.) Smaller buffer sizes give - * fast adaptation but have of course the overhead of transmitting - * trees more frequently. - * - I can't count above 4 - */ - - uInt last_lit; /* running index in l_buf */ - - ushf *d_buf; - /* Buffer for distances. To simplify the code, d_buf and l_buf have - * the same number of elements. To use different lengths, an extra flag - * array would be necessary. - */ - - ulg opt_len; /* bit length of current block with optimal trees */ - ulg static_len; /* bit length of current block with static trees */ - uInt matches; /* number of string matches in current block */ - int last_eob_len; /* bit length of EOB code for last block */ - -#ifdef DEBUG - ulg compressed_len; /* total bit length of compressed file mod 2^32 */ - ulg bits_sent; /* bit length of compressed data sent mod 2^32 */ -#endif - - ush bi_buf; - /* Output buffer. bits are inserted starting at the bottom (least - * significant bits). - */ - int bi_valid; - /* Number of valid bits in bi_buf. All bits above the last valid bit - * are always zero. - */ - -} FAR deflate_state; - -/* Output a byte on the stream. - * IN assertion: there is enough room in pending_buf. - */ -#define put_byte(s, c) {s->pending_buf[s->pending++] = (c);} - - -#define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1) -/* Minimum amount of lookahead, except at the end of the input file. - * See deflate.c for comments about the MIN_MATCH+1. - */ - -#define MAX_DIST(s) ((s)->w_size-MIN_LOOKAHEAD) -/* In order to simplify the code, particularly on 16 bit machines, match - * distances are limited to MAX_DIST instead of WSIZE. - */ - - /* in trees.c */ -void _tr_init OF((deflate_state *s)); -int _tr_tally OF((deflate_state *s, unsigned dist, unsigned lc)); -void _tr_flush_block OF((deflate_state *s, charf *buf, ulg stored_len, - int eof)); -void _tr_align OF((deflate_state *s)); -void _tr_stored_block OF((deflate_state *s, charf *buf, ulg stored_len, - int eof)); - -#define d_code(dist) \ - ((dist) < 256 ? _dist_code[dist] : _dist_code[256+((dist)>>7)]) -/* Mapping from a distance to a distance code. dist is the distance - 1 and - * must not have side effects. _dist_code[256] and _dist_code[257] are never - * used. - */ - -#ifndef DEBUG -/* Inline versions of _tr_tally for speed: */ - -#if defined(GEN_TREES_H) || !defined(STDC) - extern uch _length_code[]; - extern uch _dist_code[]; -#else - extern const uch _length_code[]; - extern const uch _dist_code[]; -#endif - -# define _tr_tally_lit(s, c, flush) \ - { uch cc = (c); \ - s->d_buf[s->last_lit] = 0; \ - s->l_buf[s->last_lit++] = cc; \ - s->dyn_ltree[cc].Freq++; \ - flush = (s->last_lit == s->lit_bufsize-1); \ - } -# define _tr_tally_dist(s, distance, length, flush) \ - { uch len = (length); \ - ush dist = (distance); \ - s->d_buf[s->last_lit] = dist; \ - s->l_buf[s->last_lit++] = len; \ - dist--; \ - s->dyn_ltree[_length_code[len]+LITERALS+1].Freq++; \ - s->dyn_dtree[d_code(dist)].Freq++; \ - flush = (s->last_lit == s->lit_bufsize-1); \ - } -#else -# define _tr_tally_lit(s, c, flush) flush = _tr_tally(s, 0, c) -# define _tr_tally_dist(s, distance, length, flush) \ - flush = _tr_tally(s, distance, length) -#endif - -#endif /* DEFLATE_H */ diff --git a/sourcepawn/third_party/zlib/gzio.c b/sourcepawn/third_party/zlib/gzio.c deleted file mode 100644 index 5e20a4aa..00000000 --- a/sourcepawn/third_party/zlib/gzio.c +++ /dev/null @@ -1,1026 +0,0 @@ -/* gzio.c -- IO on .gz files - * Copyright (C) 1995-2005 Jean-loup Gailly. - * For conditions of distribution and use, see copyright notice in zlib.h - * - * Compile this file with -DNO_GZCOMPRESS to avoid the compression code. - */ - -/* @(#) $Id$ */ - -#include - -#include "zutil.h" - -#ifdef NO_DEFLATE /* for compatibility with old definition */ -# define NO_GZCOMPRESS -#endif - -#ifndef NO_DUMMY_DECL -struct internal_state {int dummy;}; /* for buggy compilers */ -#endif - -#ifndef Z_BUFSIZE -# ifdef MAXSEG_64K -# define Z_BUFSIZE 4096 /* minimize memory usage for 16-bit DOS */ -# else -# define Z_BUFSIZE 16384 -# endif -#endif -#ifndef Z_PRINTF_BUFSIZE -# define Z_PRINTF_BUFSIZE 4096 -#endif - -#ifdef __MVS__ -# pragma map (fdopen , "\174\174FDOPEN") - FILE *fdopen(int, const char *); -#endif - -#ifndef STDC -extern voidp malloc OF((uInt size)); -extern void free OF((voidpf ptr)); -#endif - -#define ALLOC(size) malloc(size) -#define TRYFREE(p) {if (p) free(p);} - -static int const gz_magic[2] = {0x1f, 0x8b}; /* gzip magic header */ - -/* gzip flag byte */ -#define ASCII_FLAG 0x01 /* bit 0 set: file probably ascii text */ -#define HEAD_CRC 0x02 /* bit 1 set: header CRC present */ -#define EXTRA_FIELD 0x04 /* bit 2 set: extra field present */ -#define ORIG_NAME 0x08 /* bit 3 set: original file name present */ -#define COMMENT 0x10 /* bit 4 set: file comment present */ -#define RESERVED 0xE0 /* bits 5..7: reserved */ - -typedef struct gz_stream { - z_stream stream; - int z_err; /* error code for last stream operation */ - int z_eof; /* set if end of input file */ - FILE *file; /* .gz file */ - Byte *inbuf; /* input buffer */ - Byte *outbuf; /* output buffer */ - uLong crc; /* crc32 of uncompressed data */ - char *msg; /* error message */ - char *path; /* path name for debugging only */ - int transparent; /* 1 if input file is not a .gz file */ - char mode; /* 'w' or 'r' */ - z_off_t start; /* start of compressed data in file (header skipped) */ - z_off_t in; /* bytes into deflate or inflate */ - z_off_t out; /* bytes out of deflate or inflate */ - int back; /* one character push-back */ - int last; /* true if push-back is last character */ -} gz_stream; - - -local gzFile gz_open OF((const char *path, const char *mode, int fd)); -local int do_flush OF((gzFile file, int flush)); -local int get_byte OF((gz_stream *s)); -local void check_header OF((gz_stream *s)); -local int destroy OF((gz_stream *s)); -local void putLong OF((FILE *file, uLong x)); -local uLong getLong OF((gz_stream *s)); - -/* =========================================================================== - Opens a gzip (.gz) file for reading or writing. The mode parameter - is as in fopen ("rb" or "wb"). The file is given either by file descriptor - or path name (if fd == -1). - gz_open returns NULL if the file could not be opened or if there was - insufficient memory to allocate the (de)compression state; errno - can be checked to distinguish the two cases (if errno is zero, the - zlib error is Z_MEM_ERROR). -*/ -local gzFile gz_open (path, mode, fd) - const char *path; - const char *mode; - int fd; -{ - int err; - int level = Z_DEFAULT_COMPRESSION; /* compression level */ - int strategy = Z_DEFAULT_STRATEGY; /* compression strategy */ - char *p = (char*)mode; - gz_stream *s; - char fmode[80]; /* copy of mode, without the compression level */ - char *m = fmode; - - if (!path || !mode) return Z_NULL; - - s = (gz_stream *)ALLOC(sizeof(gz_stream)); - if (!s) return Z_NULL; - - s->stream.zalloc = (alloc_func)0; - s->stream.zfree = (free_func)0; - s->stream.opaque = (voidpf)0; - s->stream.next_in = s->inbuf = Z_NULL; - s->stream.next_out = s->outbuf = Z_NULL; - s->stream.avail_in = s->stream.avail_out = 0; - s->file = NULL; - s->z_err = Z_OK; - s->z_eof = 0; - s->in = 0; - s->out = 0; - s->back = EOF; - s->crc = crc32(0L, Z_NULL, 0); - s->msg = NULL; - s->transparent = 0; - - s->path = (char*)ALLOC(strlen(path)+1); - if (s->path == NULL) { - return destroy(s), (gzFile)Z_NULL; - } - strcpy(s->path, path); /* do this early for debugging */ - - s->mode = '\0'; - do { - if (*p == 'r') s->mode = 'r'; - if (*p == 'w' || *p == 'a') s->mode = 'w'; - if (*p >= '0' && *p <= '9') { - level = *p - '0'; - } else if (*p == 'f') { - strategy = Z_FILTERED; - } else if (*p == 'h') { - strategy = Z_HUFFMAN_ONLY; - } else if (*p == 'R') { - strategy = Z_RLE; - } else { - *m++ = *p; /* copy the mode */ - } - } while (*p++ && m != fmode + sizeof(fmode)); - if (s->mode == '\0') return destroy(s), (gzFile)Z_NULL; - - if (s->mode == 'w') { -#ifdef NO_GZCOMPRESS - err = Z_STREAM_ERROR; -#else - err = deflateInit2(&(s->stream), level, - Z_DEFLATED, -MAX_WBITS, DEF_MEM_LEVEL, strategy); - /* windowBits is passed < 0 to suppress zlib header */ - - s->stream.next_out = s->outbuf = (Byte*)ALLOC(Z_BUFSIZE); -#endif - if (err != Z_OK || s->outbuf == Z_NULL) { - return destroy(s), (gzFile)Z_NULL; - } - } else { - s->stream.next_in = s->inbuf = (Byte*)ALLOC(Z_BUFSIZE); - - err = inflateInit2(&(s->stream), -MAX_WBITS); - /* windowBits is passed < 0 to tell that there is no zlib header. - * Note that in this case inflate *requires* an extra "dummy" byte - * after the compressed stream in order to complete decompression and - * return Z_STREAM_END. Here the gzip CRC32 ensures that 4 bytes are - * present after the compressed stream. - */ - if (err != Z_OK || s->inbuf == Z_NULL) { - return destroy(s), (gzFile)Z_NULL; - } - } - s->stream.avail_out = Z_BUFSIZE; - - errno = 0; - s->file = fd < 0 ? F_OPEN(path, fmode) : (FILE*)fdopen(fd, fmode); - - if (s->file == NULL) { - return destroy(s), (gzFile)Z_NULL; - } - if (s->mode == 'w') { - /* Write a very simple .gz header: - */ - fprintf(s->file, "%c%c%c%c%c%c%c%c%c%c", gz_magic[0], gz_magic[1], - Z_DEFLATED, 0 /*flags*/, 0,0,0,0 /*time*/, 0 /*xflags*/, OS_CODE); - s->start = 10L; - /* We use 10L instead of ftell(s->file) to because ftell causes an - * fflush on some systems. This version of the library doesn't use - * start anyway in write mode, so this initialization is not - * necessary. - */ - } else { - check_header(s); /* skip the .gz header */ - s->start = ftell(s->file) - s->stream.avail_in; - } - - return (gzFile)s; -} - -/* =========================================================================== - Opens a gzip (.gz) file for reading or writing. -*/ -gzFile ZEXPORT gzopen (path, mode) - const char *path; - const char *mode; -{ - return gz_open (path, mode, -1); -} - -/* =========================================================================== - Associate a gzFile with the file descriptor fd. fd is not dup'ed here - to mimic the behavio(u)r of fdopen. -*/ -gzFile ZEXPORT gzdopen (fd, mode) - int fd; - const char *mode; -{ - char name[46]; /* allow for up to 128-bit integers */ - - if (fd < 0) return (gzFile)Z_NULL; - sprintf(name, "", fd); /* for debugging */ - - return gz_open (name, mode, fd); -} - -/* =========================================================================== - * Update the compression level and strategy - */ -int ZEXPORT gzsetparams (file, level, strategy) - gzFile file; - int level; - int strategy; -{ - gz_stream *s = (gz_stream*)file; - - if (s == NULL || s->mode != 'w') return Z_STREAM_ERROR; - - /* Make room to allow flushing */ - if (s->stream.avail_out == 0) { - - s->stream.next_out = s->outbuf; - if (fwrite(s->outbuf, 1, Z_BUFSIZE, s->file) != Z_BUFSIZE) { - s->z_err = Z_ERRNO; - } - s->stream.avail_out = Z_BUFSIZE; - } - - return deflateParams (&(s->stream), level, strategy); -} - -/* =========================================================================== - Read a byte from a gz_stream; update next_in and avail_in. Return EOF - for end of file. - IN assertion: the stream s has been sucessfully opened for reading. -*/ -local int get_byte(s) - gz_stream *s; -{ - if (s->z_eof) return EOF; - if (s->stream.avail_in == 0) { - errno = 0; - s->stream.avail_in = (uInt)fread(s->inbuf, 1, Z_BUFSIZE, s->file); - if (s->stream.avail_in == 0) { - s->z_eof = 1; - if (ferror(s->file)) s->z_err = Z_ERRNO; - return EOF; - } - s->stream.next_in = s->inbuf; - } - s->stream.avail_in--; - return *(s->stream.next_in)++; -} - -/* =========================================================================== - Check the gzip header of a gz_stream opened for reading. Set the stream - mode to transparent if the gzip magic header is not present; set s->err - to Z_DATA_ERROR if the magic header is present but the rest of the header - is incorrect. - IN assertion: the stream s has already been created sucessfully; - s->stream.avail_in is zero for the first time, but may be non-zero - for concatenated .gz files. -*/ -local void check_header(s) - gz_stream *s; -{ - int method; /* method byte */ - int flags; /* flags byte */ - uInt len; - int c; - - /* Assure two bytes in the buffer so we can peek ahead -- handle case - where first byte of header is at the end of the buffer after the last - gzip segment */ - len = s->stream.avail_in; - if (len < 2) { - if (len) s->inbuf[0] = s->stream.next_in[0]; - errno = 0; - len = (uInt)fread(s->inbuf + len, 1, Z_BUFSIZE >> len, s->file); - if (len == 0 && ferror(s->file)) s->z_err = Z_ERRNO; - s->stream.avail_in += len; - s->stream.next_in = s->inbuf; - if (s->stream.avail_in < 2) { - s->transparent = s->stream.avail_in; - return; - } - } - - /* Peek ahead to check the gzip magic header */ - if (s->stream.next_in[0] != gz_magic[0] || - s->stream.next_in[1] != gz_magic[1]) { - s->transparent = 1; - return; - } - s->stream.avail_in -= 2; - s->stream.next_in += 2; - - /* Check the rest of the gzip header */ - method = get_byte(s); - flags = get_byte(s); - if (method != Z_DEFLATED || (flags & RESERVED) != 0) { - s->z_err = Z_DATA_ERROR; - return; - } - - /* Discard time, xflags and OS code: */ - for (len = 0; len < 6; len++) (void)get_byte(s); - - if ((flags & EXTRA_FIELD) != 0) { /* skip the extra field */ - len = (uInt)get_byte(s); - len += ((uInt)get_byte(s))<<8; - /* len is garbage if EOF but the loop below will quit anyway */ - while (len-- != 0 && get_byte(s) != EOF) ; - } - if ((flags & ORIG_NAME) != 0) { /* skip the original file name */ - while ((c = get_byte(s)) != 0 && c != EOF) ; - } - if ((flags & COMMENT) != 0) { /* skip the .gz file comment */ - while ((c = get_byte(s)) != 0 && c != EOF) ; - } - if ((flags & HEAD_CRC) != 0) { /* skip the header crc */ - for (len = 0; len < 2; len++) (void)get_byte(s); - } - s->z_err = s->z_eof ? Z_DATA_ERROR : Z_OK; -} - - /* =========================================================================== - * Cleanup then free the given gz_stream. Return a zlib error code. - Try freeing in the reverse order of allocations. - */ -local int destroy (s) - gz_stream *s; -{ - int err = Z_OK; - - if (!s) return Z_STREAM_ERROR; - - TRYFREE(s->msg); - - if (s->stream.state != NULL) { - if (s->mode == 'w') { -#ifdef NO_GZCOMPRESS - err = Z_STREAM_ERROR; -#else - err = deflateEnd(&(s->stream)); -#endif - } else if (s->mode == 'r') { - err = inflateEnd(&(s->stream)); - } - } - if (s->file != NULL && fclose(s->file)) { -#ifdef ESPIPE - if (errno != ESPIPE) /* fclose is broken for pipes in HP/UX */ -#endif - err = Z_ERRNO; - } - if (s->z_err < 0) err = s->z_err; - - TRYFREE(s->inbuf); - TRYFREE(s->outbuf); - TRYFREE(s->path); - TRYFREE(s); - return err; -} - -/* =========================================================================== - Reads the given number of uncompressed bytes from the compressed file. - gzread returns the number of bytes actually read (0 for end of file). -*/ -int ZEXPORT gzread (file, buf, len) - gzFile file; - voidp buf; - unsigned len; -{ - gz_stream *s = (gz_stream*)file; - Bytef *start = (Bytef*)buf; /* starting point for crc computation */ - Byte *next_out; /* == stream.next_out but not forced far (for MSDOS) */ - - if (s == NULL || s->mode != 'r') return Z_STREAM_ERROR; - - if (s->z_err == Z_DATA_ERROR || s->z_err == Z_ERRNO) return -1; - if (s->z_err == Z_STREAM_END) return 0; /* EOF */ - - next_out = (Byte*)buf; - s->stream.next_out = (Bytef*)buf; - s->stream.avail_out = len; - - if (s->stream.avail_out && s->back != EOF) { - *next_out++ = s->back; - s->stream.next_out++; - s->stream.avail_out--; - s->back = EOF; - s->out++; - start++; - if (s->last) { - s->z_err = Z_STREAM_END; - return 1; - } - } - - while (s->stream.avail_out != 0) { - - if (s->transparent) { - /* Copy first the lookahead bytes: */ - uInt n = s->stream.avail_in; - if (n > s->stream.avail_out) n = s->stream.avail_out; - if (n > 0) { - zmemcpy(s->stream.next_out, s->stream.next_in, n); - next_out += n; - s->stream.next_out = next_out; - s->stream.next_in += n; - s->stream.avail_out -= n; - s->stream.avail_in -= n; - } - if (s->stream.avail_out > 0) { - s->stream.avail_out -= - (uInt)fread(next_out, 1, s->stream.avail_out, s->file); - } - len -= s->stream.avail_out; - s->in += len; - s->out += len; - if (len == 0) s->z_eof = 1; - return (int)len; - } - if (s->stream.avail_in == 0 && !s->z_eof) { - - errno = 0; - s->stream.avail_in = (uInt)fread(s->inbuf, 1, Z_BUFSIZE, s->file); - if (s->stream.avail_in == 0) { - s->z_eof = 1; - if (ferror(s->file)) { - s->z_err = Z_ERRNO; - break; - } - } - s->stream.next_in = s->inbuf; - } - s->in += s->stream.avail_in; - s->out += s->stream.avail_out; - s->z_err = inflate(&(s->stream), Z_NO_FLUSH); - s->in -= s->stream.avail_in; - s->out -= s->stream.avail_out; - - if (s->z_err == Z_STREAM_END) { - /* Check CRC and original size */ - s->crc = crc32(s->crc, start, (uInt)(s->stream.next_out - start)); - start = s->stream.next_out; - - if (getLong(s) != s->crc) { - s->z_err = Z_DATA_ERROR; - } else { - (void)getLong(s); - /* The uncompressed length returned by above getlong() may be - * different from s->out in case of concatenated .gz files. - * Check for such files: - */ - check_header(s); - if (s->z_err == Z_OK) { - inflateReset(&(s->stream)); - s->crc = crc32(0L, Z_NULL, 0); - } - } - } - if (s->z_err != Z_OK || s->z_eof) break; - } - s->crc = crc32(s->crc, start, (uInt)(s->stream.next_out - start)); - - if (len == s->stream.avail_out && - (s->z_err == Z_DATA_ERROR || s->z_err == Z_ERRNO)) - return -1; - return (int)(len - s->stream.avail_out); -} - - -/* =========================================================================== - Reads one byte from the compressed file. gzgetc returns this byte - or -1 in case of end of file or error. -*/ -int ZEXPORT gzgetc(file) - gzFile file; -{ - unsigned char c; - - return gzread(file, &c, 1) == 1 ? c : -1; -} - - -/* =========================================================================== - Push one byte back onto the stream. -*/ -int ZEXPORT gzungetc(c, file) - int c; - gzFile file; -{ - gz_stream *s = (gz_stream*)file; - - if (s == NULL || s->mode != 'r' || c == EOF || s->back != EOF) return EOF; - s->back = c; - s->out--; - s->last = (s->z_err == Z_STREAM_END); - if (s->last) s->z_err = Z_OK; - s->z_eof = 0; - return c; -} - - -/* =========================================================================== - Reads bytes from the compressed file until len-1 characters are - read, or a newline character is read and transferred to buf, or an - end-of-file condition is encountered. The string is then terminated - with a null character. - gzgets returns buf, or Z_NULL in case of error. - - The current implementation is not optimized at all. -*/ -char * ZEXPORT gzgets(file, buf, len) - gzFile file; - char *buf; - int len; -{ - char *b = buf; - if (buf == Z_NULL || len <= 0) return Z_NULL; - - while (--len > 0 && gzread(file, buf, 1) == 1 && *buf++ != '\n') ; - *buf = '\0'; - return b == buf && len > 0 ? Z_NULL : b; -} - - -#ifndef NO_GZCOMPRESS -/* =========================================================================== - Writes the given number of uncompressed bytes into the compressed file. - gzwrite returns the number of bytes actually written (0 in case of error). -*/ -int ZEXPORT gzwrite (file, buf, len) - gzFile file; - voidpc buf; - unsigned len; -{ - gz_stream *s = (gz_stream*)file; - - if (s == NULL || s->mode != 'w') return Z_STREAM_ERROR; - - s->stream.next_in = (Bytef*)buf; - s->stream.avail_in = len; - - while (s->stream.avail_in != 0) { - - if (s->stream.avail_out == 0) { - - s->stream.next_out = s->outbuf; - if (fwrite(s->outbuf, 1, Z_BUFSIZE, s->file) != Z_BUFSIZE) { - s->z_err = Z_ERRNO; - break; - } - s->stream.avail_out = Z_BUFSIZE; - } - s->in += s->stream.avail_in; - s->out += s->stream.avail_out; - s->z_err = deflate(&(s->stream), Z_NO_FLUSH); - s->in -= s->stream.avail_in; - s->out -= s->stream.avail_out; - if (s->z_err != Z_OK) break; - } - s->crc = crc32(s->crc, (const Bytef *)buf, len); - - return (int)(len - s->stream.avail_in); -} - - -/* =========================================================================== - Converts, formats, and writes the args to the compressed file under - control of the format string, as in fprintf. gzprintf returns the number of - uncompressed bytes actually written (0 in case of error). -*/ -#ifdef STDC -#include - -int ZEXPORTVA gzprintf (gzFile file, const char *format, /* args */ ...) -{ - char buf[Z_PRINTF_BUFSIZE]; - va_list va; - int len; - - buf[sizeof(buf) - 1] = 0; - va_start(va, format); -#ifdef NO_vsnprintf -# ifdef HAS_vsprintf_void - (void)vsprintf(buf, format, va); - va_end(va); - for (len = 0; len < sizeof(buf); len++) - if (buf[len] == 0) break; -# else - len = vsprintf(buf, format, va); - va_end(va); -# endif -#else -# ifdef HAS_vsnprintf_void - (void)vsnprintf(buf, sizeof(buf), format, va); - va_end(va); - len = strlen(buf); -# else - len = vsnprintf(buf, sizeof(buf), format, va); - va_end(va); -# endif -#endif - if (len <= 0 || len >= (int)sizeof(buf) || buf[sizeof(buf) - 1] != 0) - return 0; - return gzwrite(file, buf, (unsigned)len); -} -#else /* not ANSI C */ - -int ZEXPORTVA gzprintf (file, format, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, - a11, a12, a13, a14, a15, a16, a17, a18, a19, a20) - gzFile file; - const char *format; - int a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, - a11, a12, a13, a14, a15, a16, a17, a18, a19, a20; -{ - char buf[Z_PRINTF_BUFSIZE]; - int len; - - buf[sizeof(buf) - 1] = 0; -#ifdef NO_snprintf -# ifdef HAS_sprintf_void - sprintf(buf, format, a1, a2, a3, a4, a5, a6, a7, a8, - a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20); - for (len = 0; len < sizeof(buf); len++) - if (buf[len] == 0) break; -# else - len = sprintf(buf, format, a1, a2, a3, a4, a5, a6, a7, a8, - a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20); -# endif -#else -# ifdef HAS_snprintf_void - snprintf(buf, sizeof(buf), format, a1, a2, a3, a4, a5, a6, a7, a8, - a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20); - len = strlen(buf); -# else - len = snprintf(buf, sizeof(buf), format, a1, a2, a3, a4, a5, a6, a7, a8, - a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20); -# endif -#endif - if (len <= 0 || len >= sizeof(buf) || buf[sizeof(buf) - 1] != 0) - return 0; - return gzwrite(file, buf, len); -} -#endif - -/* =========================================================================== - Writes c, converted to an unsigned char, into the compressed file. - gzputc returns the value that was written, or -1 in case of error. -*/ -int ZEXPORT gzputc(file, c) - gzFile file; - int c; -{ - unsigned char cc = (unsigned char) c; /* required for big endian systems */ - - return gzwrite(file, &cc, 1) == 1 ? (int)cc : -1; -} - - -/* =========================================================================== - Writes the given null-terminated string to the compressed file, excluding - the terminating null character. - gzputs returns the number of characters written, or -1 in case of error. -*/ -int ZEXPORT gzputs(file, s) - gzFile file; - const char *s; -{ - return gzwrite(file, (char*)s, (unsigned)strlen(s)); -} - - -/* =========================================================================== - Flushes all pending output into the compressed file. The parameter - flush is as in the deflate() function. -*/ -local int do_flush (file, flush) - gzFile file; - int flush; -{ - uInt len; - int done = 0; - gz_stream *s = (gz_stream*)file; - - if (s == NULL || s->mode != 'w') return Z_STREAM_ERROR; - - s->stream.avail_in = 0; /* should be zero already anyway */ - - for (;;) { - len = Z_BUFSIZE - s->stream.avail_out; - - if (len != 0) { - if ((uInt)fwrite(s->outbuf, 1, len, s->file) != len) { - s->z_err = Z_ERRNO; - return Z_ERRNO; - } - s->stream.next_out = s->outbuf; - s->stream.avail_out = Z_BUFSIZE; - } - if (done) break; - s->out += s->stream.avail_out; - s->z_err = deflate(&(s->stream), flush); - s->out -= s->stream.avail_out; - - /* Ignore the second of two consecutive flushes: */ - if (len == 0 && s->z_err == Z_BUF_ERROR) s->z_err = Z_OK; - - /* deflate has finished flushing only when it hasn't used up - * all the available space in the output buffer: - */ - done = (s->stream.avail_out != 0 || s->z_err == Z_STREAM_END); - - if (s->z_err != Z_OK && s->z_err != Z_STREAM_END) break; - } - return s->z_err == Z_STREAM_END ? Z_OK : s->z_err; -} - -int ZEXPORT gzflush (file, flush) - gzFile file; - int flush; -{ - gz_stream *s = (gz_stream*)file; - int err = do_flush (file, flush); - - if (err) return err; - fflush(s->file); - return s->z_err == Z_STREAM_END ? Z_OK : s->z_err; -} -#endif /* NO_GZCOMPRESS */ - -/* =========================================================================== - Sets the starting position for the next gzread or gzwrite on the given - compressed file. The offset represents a number of bytes in the - gzseek returns the resulting offset location as measured in bytes from - the beginning of the uncompressed stream, or -1 in case of error. - SEEK_END is not implemented, returns error. - In this version of the library, gzseek can be extremely slow. -*/ -z_off_t ZEXPORT gzseek (file, offset, whence) - gzFile file; - z_off_t offset; - int whence; -{ - gz_stream *s = (gz_stream*)file; - - if (s == NULL || whence == SEEK_END || - s->z_err == Z_ERRNO || s->z_err == Z_DATA_ERROR) { - return -1L; - } - - if (s->mode == 'w') { -#ifdef NO_GZCOMPRESS - return -1L; -#else - if (whence == SEEK_SET) { - offset -= s->in; - } - if (offset < 0) return -1L; - - /* At this point, offset is the number of zero bytes to write. */ - if (s->inbuf == Z_NULL) { - s->inbuf = (Byte*)ALLOC(Z_BUFSIZE); /* for seeking */ - if (s->inbuf == Z_NULL) return -1L; - zmemzero(s->inbuf, Z_BUFSIZE); - } - while (offset > 0) { - uInt size = Z_BUFSIZE; - if (offset < Z_BUFSIZE) size = (uInt)offset; - - size = gzwrite(file, s->inbuf, size); - if (size == 0) return -1L; - - offset -= size; - } - return s->in; -#endif - } - /* Rest of function is for reading only */ - - /* compute absolute position */ - if (whence == SEEK_CUR) { - offset += s->out; - } - if (offset < 0) return -1L; - - if (s->transparent) { - /* map to fseek */ - s->back = EOF; - s->stream.avail_in = 0; - s->stream.next_in = s->inbuf; - if (fseek(s->file, offset, SEEK_SET) < 0) return -1L; - - s->in = s->out = offset; - return offset; - } - - /* For a negative seek, rewind and use positive seek */ - if (offset >= s->out) { - offset -= s->out; - } else if (gzrewind(file) < 0) { - return -1L; - } - /* offset is now the number of bytes to skip. */ - - if (offset != 0 && s->outbuf == Z_NULL) { - s->outbuf = (Byte*)ALLOC(Z_BUFSIZE); - if (s->outbuf == Z_NULL) return -1L; - } - if (offset && s->back != EOF) { - s->back = EOF; - s->out++; - offset--; - if (s->last) s->z_err = Z_STREAM_END; - } - while (offset > 0) { - int size = Z_BUFSIZE; - if (offset < Z_BUFSIZE) size = (int)offset; - - size = gzread(file, s->outbuf, (uInt)size); - if (size <= 0) return -1L; - offset -= size; - } - return s->out; -} - -/* =========================================================================== - Rewinds input file. -*/ -int ZEXPORT gzrewind (file) - gzFile file; -{ - gz_stream *s = (gz_stream*)file; - - if (s == NULL || s->mode != 'r') return -1; - - s->z_err = Z_OK; - s->z_eof = 0; - s->back = EOF; - s->stream.avail_in = 0; - s->stream.next_in = s->inbuf; - s->crc = crc32(0L, Z_NULL, 0); - if (!s->transparent) (void)inflateReset(&s->stream); - s->in = 0; - s->out = 0; - return fseek(s->file, s->start, SEEK_SET); -} - -/* =========================================================================== - Returns the starting position for the next gzread or gzwrite on the - given compressed file. This position represents a number of bytes in the - uncompressed data stream. -*/ -z_off_t ZEXPORT gztell (file) - gzFile file; -{ - return gzseek(file, 0L, SEEK_CUR); -} - -/* =========================================================================== - Returns 1 when EOF has previously been detected reading the given - input stream, otherwise zero. -*/ -int ZEXPORT gzeof (file) - gzFile file; -{ - gz_stream *s = (gz_stream*)file; - - /* With concatenated compressed files that can have embedded - * crc trailers, z_eof is no longer the only/best indicator of EOF - * on a gz_stream. Handle end-of-stream error explicitly here. - */ - if (s == NULL || s->mode != 'r') return 0; - if (s->z_eof) return 1; - return s->z_err == Z_STREAM_END; -} - -/* =========================================================================== - Returns 1 if reading and doing so transparently, otherwise zero. -*/ -int ZEXPORT gzdirect (file) - gzFile file; -{ - gz_stream *s = (gz_stream*)file; - - if (s == NULL || s->mode != 'r') return 0; - return s->transparent; -} - -/* =========================================================================== - Outputs a long in LSB order to the given file -*/ -local void putLong (file, x) - FILE *file; - uLong x; -{ - int n; - for (n = 0; n < 4; n++) { - fputc((int)(x & 0xff), file); - x >>= 8; - } -} - -/* =========================================================================== - Reads a long in LSB order from the given gz_stream. Sets z_err in case - of error. -*/ -local uLong getLong (s) - gz_stream *s; -{ - uLong x = (uLong)get_byte(s); - int c; - - x += ((uLong)get_byte(s))<<8; - x += ((uLong)get_byte(s))<<16; - c = get_byte(s); - if (c == EOF) s->z_err = Z_DATA_ERROR; - x += ((uLong)c)<<24; - return x; -} - -/* =========================================================================== - Flushes all pending output if necessary, closes the compressed file - and deallocates all the (de)compression state. -*/ -int ZEXPORT gzclose (file) - gzFile file; -{ - gz_stream *s = (gz_stream*)file; - - if (s == NULL) return Z_STREAM_ERROR; - - if (s->mode == 'w') { -#ifdef NO_GZCOMPRESS - return Z_STREAM_ERROR; -#else - if (do_flush (file, Z_FINISH) != Z_OK) - return destroy((gz_stream*)file); - - putLong (s->file, s->crc); - putLong (s->file, (uLong)(s->in & 0xffffffff)); -#endif - } - return destroy((gz_stream*)file); -} - -#ifdef STDC -# define zstrerror(errnum) strerror(errnum) -#else -# define zstrerror(errnum) "" -#endif - -/* =========================================================================== - Returns the error message for the last error which occurred on the - given compressed file. errnum is set to zlib error number. If an - error occurred in the file system and not in the compression library, - errnum is set to Z_ERRNO and the application may consult errno - to get the exact error code. -*/ -const char * ZEXPORT gzerror (file, errnum) - gzFile file; - int *errnum; -{ - char *m; - gz_stream *s = (gz_stream*)file; - - if (s == NULL) { - *errnum = Z_STREAM_ERROR; - return (const char*)ERR_MSG(Z_STREAM_ERROR); - } - *errnum = s->z_err; - if (*errnum == Z_OK) return (const char*)""; - - m = (char*)(*errnum == Z_ERRNO ? zstrerror(errno) : s->stream.msg); - - if (m == NULL || *m == '\0') m = (char*)ERR_MSG(s->z_err); - - TRYFREE(s->msg); - s->msg = (char*)ALLOC(strlen(s->path) + strlen(m) + 3); - if (s->msg == Z_NULL) return (const char*)ERR_MSG(Z_MEM_ERROR); - strcpy(s->msg, s->path); - strcat(s->msg, ": "); - strcat(s->msg, m); - return (const char*)s->msg; -} - -/* =========================================================================== - Clear the error and end-of-file flags, and do the same for the real file. -*/ -void ZEXPORT gzclearerr (file) - gzFile file; -{ - gz_stream *s = (gz_stream*)file; - - if (s == NULL) return; - if (s->z_err != Z_STREAM_END) s->z_err = Z_OK; - s->z_eof = 0; - clearerr(s->file); -} diff --git a/sourcepawn/third_party/zlib/infback.c b/sourcepawn/third_party/zlib/infback.c deleted file mode 100644 index 0056928e..00000000 --- a/sourcepawn/third_party/zlib/infback.c +++ /dev/null @@ -1,624 +0,0 @@ -/* infback.c -- inflate using a call-back interface - * Copyright (C) 1995-2005 Mark Adler - * For conditions of distribution and use, see copyright notice in zlib.h - */ - -/* - This code is largely copied from inflate.c. Normally either infback.o or - inflate.o would be linked into an application--not both. The interface - with inffast.c is retained so that optimized assembler-coded versions of - inflate_fast() can be used with either inflate.c or infback.c. - */ - -#include -#include "zutil.h" -#include "inftrees.h" -#include "inflate.h" -#include "inffast.h" - -/* function prototypes */ -local void fixedtables OF((struct inflate_state FAR *state)); - -/* - strm provides memory allocation functions in zalloc and zfree, or - Z_NULL to use the library memory allocation functions. - - windowBits is in the range 8..15, and window is a user-supplied - window and output buffer that is 2**windowBits bytes. - */ -int ZEXPORT inflateBackInit_(strm, windowBits, window, version, stream_size) -z_streamp strm; -int windowBits; -unsigned char FAR *window; -const char *version; -int stream_size; -{ - struct inflate_state FAR *state; - - if (version == Z_NULL || version[0] != ZLIB_VERSION[0] || - stream_size != (int)(sizeof(z_stream))) - return Z_VERSION_ERROR; - if (strm == Z_NULL || window == Z_NULL || - windowBits < 8 || windowBits > 15) - return Z_STREAM_ERROR; - strm->msg = Z_NULL; /* in case we return an error */ - if (strm->zalloc == (alloc_func)0) { - strm->zalloc = zcalloc; - strm->opaque = (voidpf)0; - } - if (strm->zfree == (free_func)0) strm->zfree = zcfree; - state = (struct inflate_state FAR *)ZALLOC(strm, 1, - sizeof(struct inflate_state)); - if (state == Z_NULL) return Z_MEM_ERROR; - Tracev((stderr, "inflate: allocated\n")); - strm->state = (struct internal_state FAR *)state; - state->dmax = 32768U; - state->wbits = windowBits; - state->wsize = 1U << windowBits; - state->window = window; - state->write = 0; - state->whave = 0; - return Z_OK; -} - -/* - Return state with length and distance decoding tables and index sizes set to - fixed code decoding. Normally this returns fixed tables from inffixed.h. - If BUILDFIXED is defined, then instead this routine builds the tables the - first time it's called, and returns those tables the first time and - thereafter. This reduces the size of the code by about 2K bytes, in - exchange for a little execution time. However, BUILDFIXED should not be - used for threaded applications, since the rewriting of the tables and virgin - may not be thread-safe. - */ -local void fixedtables(state) -struct inflate_state FAR *state; -{ -#ifdef BUILDFIXED - static int virgin = 1; - static code *lenfix, *distfix; - static code fixed[544]; - - /* build fixed huffman tables if first call (may not be thread safe) */ - if (virgin) { - unsigned sym, bits; - static code *next; - - /* literal/length table */ - sym = 0; - while (sym < 144) state->lens[sym++] = 8; - while (sym < 256) state->lens[sym++] = 9; - while (sym < 280) state->lens[sym++] = 7; - while (sym < 288) state->lens[sym++] = 8; - next = fixed; - lenfix = next; - bits = 9; - inflate_table(LENS, state->lens, 288, &(next), &(bits), state->work); - - /* distance table */ - sym = 0; - while (sym < 32) state->lens[sym++] = 5; - distfix = next; - bits = 5; - inflate_table(DISTS, state->lens, 32, &(next), &(bits), state->work); - - /* do this just once */ - virgin = 0; - } -#else /* !BUILDFIXED */ -# include "inffixed.h" -#endif /* BUILDFIXED */ - state->lencode = lenfix; - state->lenbits = 9; - state->distcode = distfix; - state->distbits = 5; -} - -/* Macros for inflateBack(): */ - -/* Load returned state from inflate_fast() */ -#define LOAD() \ - do { \ - put = strm->next_out; \ - left = strm->avail_out; \ - next = strm->next_in; \ - have = strm->avail_in; \ - hold = state->hold; \ - bits = state->bits; \ - } while (0) - -/* Set state from registers for inflate_fast() */ -#define RESTORE() \ - do { \ - strm->next_out = put; \ - strm->avail_out = left; \ - strm->next_in = next; \ - strm->avail_in = have; \ - state->hold = hold; \ - state->bits = bits; \ - } while (0) - -/* Clear the input bit accumulator */ -#define INITBITS() \ - do { \ - hold = 0; \ - bits = 0; \ - } while (0) - -/* Assure that some input is available. If input is requested, but denied, - then return a Z_BUF_ERROR from inflateBack(). */ -#define PULL() \ - do { \ - if (have == 0) { \ - have = in(in_desc, &next); \ - if (have == 0) { \ - next = Z_NULL; \ - ret = Z_BUF_ERROR; \ - goto inf_leave; \ - } \ - } \ - } while (0) - -/* Get a byte of input into the bit accumulator, or return from inflateBack() - with an error if there is no input available. */ -#define PULLBYTE() \ - do { \ - PULL(); \ - have--; \ - hold += (unsigned long)(*next++) << bits; \ - bits += 8; \ - } while (0) - -/* Assure that there are at least n bits in the bit accumulator. If there is - not enough available input to do that, then return from inflateBack() with - an error. */ -#define NEEDBITS(n) \ - do { \ - while (bits < (unsigned)(n)) \ - PULLBYTE(); \ - } while (0) - -/* Return the low n bits of the bit accumulator (n < 16) */ -#define BITS(n) \ - ((unsigned)hold & ((1U << (n)) - 1)) - -/* Remove n bits from the bit accumulator */ -#define DROPBITS(n) \ - do { \ - hold >>= (n); \ - bits -= (unsigned)(n); \ - } while (0) - -/* Remove zero to seven bits as needed to go to a byte boundary */ -#define BYTEBITS() \ - do { \ - hold >>= bits & 7; \ - bits -= bits & 7; \ - } while (0) - -/* Assure that some output space is available, by writing out the window - if it's full. If the write fails, return from inflateBack() with a - Z_BUF_ERROR. */ -#define ROOM() \ - do { \ - if (left == 0) { \ - put = state->window; \ - left = state->wsize; \ - state->whave = left; \ - if (out(out_desc, put, left)) { \ - ret = Z_BUF_ERROR; \ - goto inf_leave; \ - } \ - } \ - } while (0) - -/* - strm provides the memory allocation functions and window buffer on input, - and provides information on the unused input on return. For Z_DATA_ERROR - returns, strm will also provide an error message. - - in() and out() are the call-back input and output functions. When - inflateBack() needs more input, it calls in(). When inflateBack() has - filled the window with output, or when it completes with data in the - window, it calls out() to write out the data. The application must not - change the provided input until in() is called again or inflateBack() - returns. The application must not change the window/output buffer until - inflateBack() returns. - - in() and out() are called with a descriptor parameter provided in the - inflateBack() call. This parameter can be a structure that provides the - information required to do the read or write, as well as accumulated - information on the input and output such as totals and check values. - - in() should return zero on failure. out() should return non-zero on - failure. If either in() or out() fails, than inflateBack() returns a - Z_BUF_ERROR. strm->next_in can be checked for Z_NULL to see whether it - was in() or out() that caused in the error. Otherwise, inflateBack() - returns Z_STREAM_END on success, Z_DATA_ERROR for an deflate format - error, or Z_MEM_ERROR if it could not allocate memory for the state. - inflateBack() can also return Z_STREAM_ERROR if the input parameters - are not correct, i.e. strm is Z_NULL or the state was not initialized. - */ -int ZEXPORT inflateBack(strm, in, in_desc, out, out_desc) -z_streamp strm; -in_func in; -void FAR *in_desc; -out_func out; -void FAR *out_desc; -{ - struct inflate_state FAR *state; - unsigned char FAR *next; /* next input */ - unsigned char FAR *put; /* next output */ - unsigned have, left; /* available input and output */ - unsigned long hold; /* bit buffer */ - unsigned bits; /* bits in bit buffer */ - unsigned copy; /* number of stored or match bytes to copy */ - unsigned char FAR *from; /* where to copy match bytes from */ - code this; /* current decoding table entry */ - code last; /* parent table entry */ - unsigned len; /* length to copy for repeats, bits to drop */ - int ret; /* return code */ - static const unsigned short order[19] = /* permutation of code lengths */ - {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15}; - - /* Check that the strm exists and that the state was initialized */ - if (strm == Z_NULL || strm->state == Z_NULL) - return Z_STREAM_ERROR; - state = (struct inflate_state FAR *)strm->state; - - /* Reset the state */ - strm->msg = Z_NULL; - state->mode = TYPE; - state->last = 0; - state->whave = 0; - next = strm->next_in; - have = next != Z_NULL ? strm->avail_in : 0; - hold = 0; - bits = 0; - put = state->window; - left = state->wsize; - - /* Inflate until end of block marked as last */ - for (;;) - switch (state->mode) { - case TYPE: - /* determine and dispatch block type */ - if (state->last) { - BYTEBITS(); - state->mode = DONE; - break; - } - NEEDBITS(3); - state->last = BITS(1); - DROPBITS(1); - switch (BITS(2)) { - case 0: /* stored block */ - Tracev((stderr, "inflate: stored block%s\n", - state->last ? " (last)" : "")); - state->mode = STORED; - break; - case 1: /* fixed block */ - fixedtables(state); - Tracev((stderr, "inflate: fixed codes block%s\n", - state->last ? " (last)" : "")); - state->mode = LEN; /* decode codes */ - break; - case 2: /* dynamic block */ - Tracev((stderr, "inflate: dynamic codes block%s\n", - state->last ? " (last)" : "")); - state->mode = TABLE; - break; - case 3: - strm->msg = (char *)"invalid block type"; - state->mode = BAD; - } - DROPBITS(2); - break; - - case STORED: - /* get and verify stored block length */ - BYTEBITS(); /* go to byte boundary */ - NEEDBITS(32); - if ((hold & 0xffff) != ((hold >> 16) ^ 0xffff)) { - strm->msg = (char *)"invalid stored block lengths"; - state->mode = BAD; - break; - } - state->length = (unsigned)hold & 0xffff; - Tracev((stderr, "inflate: stored length %u\n", - state->length)); - INITBITS(); - - /* copy stored block from input to output */ - while (state->length != 0) { - copy = state->length; - PULL(); - ROOM(); - if (copy > have) copy = have; - if (copy > left) copy = left; - zmemcpy(put, next, copy); - have -= copy; - next += copy; - left -= copy; - put += copy; - state->length -= copy; - } - Tracev((stderr, "inflate: stored end\n")); - state->mode = TYPE; - break; - - case TABLE: - /* get dynamic table entries descriptor */ - NEEDBITS(14); - state->nlen = BITS(5) + 257; - DROPBITS(5); - state->ndist = BITS(5) + 1; - DROPBITS(5); - state->ncode = BITS(4) + 4; - DROPBITS(4); -#ifndef PKZIP_BUG_WORKAROUND - if (state->nlen > 286 || state->ndist > 30) { - strm->msg = (char *)"too many length or distance symbols"; - state->mode = BAD; - break; - } -#endif - Tracev((stderr, "inflate: table sizes ok\n")); - - /* get code length code lengths (not a typo) */ - state->have = 0; - while (state->have < state->ncode) { - NEEDBITS(3); - state->lens[order[state->have++]] = (unsigned short)BITS(3); - DROPBITS(3); - } - while (state->have < 19) - state->lens[order[state->have++]] = 0; - state->next = state->codes; - state->lencode = (code const FAR *)(state->next); - state->lenbits = 7; - ret = inflate_table(CODES, state->lens, 19, &(state->next), - &(state->lenbits), state->work); - if (ret) { - strm->msg = (char *)"invalid code lengths set"; - state->mode = BAD; - break; - } - Tracev((stderr, "inflate: code lengths ok\n")); - - /* get length and distance code code lengths */ - state->have = 0; - while (state->have < state->nlen + state->ndist) { - for (;;) { - this = state->lencode[BITS(state->lenbits)]; - if ((unsigned)(this.bits) <= bits) break; - PULLBYTE(); - } - if (this.val < 16) { - NEEDBITS(this.bits); - DROPBITS(this.bits); - state->lens[state->have++] = this.val; - } - else { - if (this.val == 16) { - NEEDBITS(this.bits + 2); - DROPBITS(this.bits); - if (state->have == 0) { - strm->msg = (char *)"invalid bit length repeat"; - state->mode = BAD; - break; - } - len = (unsigned)(state->lens[state->have - 1]); - copy = 3 + BITS(2); - DROPBITS(2); - } - else if (this.val == 17) { - NEEDBITS(this.bits + 3); - DROPBITS(this.bits); - len = 0; - copy = 3 + BITS(3); - DROPBITS(3); - } - else { - NEEDBITS(this.bits + 7); - DROPBITS(this.bits); - len = 0; - copy = 11 + BITS(7); - DROPBITS(7); - } - if (state->have + copy > state->nlen + state->ndist) { - strm->msg = (char *)"invalid bit length repeat"; - state->mode = BAD; - break; - } - while (copy--) - state->lens[state->have++] = (unsigned short)len; - } - } - - /* handle error breaks in while */ - if (state->mode == BAD) break; - - /* build code tables */ - state->next = state->codes; - state->lencode = (code const FAR *)(state->next); - state->lenbits = 9; - ret = inflate_table(LENS, state->lens, state->nlen, &(state->next), - &(state->lenbits), state->work); - if (ret) { - strm->msg = (char *)"invalid literal/lengths set"; - state->mode = BAD; - break; - } - state->distcode = (code const FAR *)(state->next); - state->distbits = 6; - ret = inflate_table(DISTS, state->lens + state->nlen, state->ndist, - &(state->next), &(state->distbits), state->work); - if (ret) { - strm->msg = (char *)"invalid distances set"; - state->mode = BAD; - break; - } - Tracev((stderr, "inflate: codes ok\n")); - state->mode = LEN; - - case LEN: - /* use inflate_fast() if we have enough input and output */ - if (have >= 6 && left >= 258) { - RESTORE(); - if (state->whave < state->wsize) - state->whave = state->wsize - left; - inflate_fast(strm, state->wsize); - LOAD(); - break; - } - - /* get a literal, length, or end-of-block code */ - for (;;) { - this = state->lencode[BITS(state->lenbits)]; - if ((unsigned)(this.bits) <= bits) break; - PULLBYTE(); - } - if (this.op && (this.op & 0xf0) == 0) { - last = this; - for (;;) { - this = state->lencode[last.val + - (BITS(last.bits + last.op) >> last.bits)]; - if ((unsigned)(last.bits + this.bits) <= bits) break; - PULLBYTE(); - } - DROPBITS(last.bits); - } - DROPBITS(this.bits); - state->length = (unsigned)this.val; - - /* process literal */ - if (this.op == 0) { - Tracevv((stderr, this.val >= 0x20 && this.val < 0x7f ? - "inflate: literal '%c'\n" : - "inflate: literal 0x%02x\n", this.val)); - ROOM(); - *put++ = (unsigned char)(state->length); - left--; - state->mode = LEN; - break; - } - - /* process end of block */ - if (this.op & 32) { - Tracevv((stderr, "inflate: end of block\n")); - state->mode = TYPE; - break; - } - - /* invalid code */ - if (this.op & 64) { - strm->msg = (char *)"invalid literal/length code"; - state->mode = BAD; - break; - } - - /* length code -- get extra bits, if any */ - state->extra = (unsigned)(this.op) & 15; - if (state->extra != 0) { - NEEDBITS(state->extra); - state->length += BITS(state->extra); - DROPBITS(state->extra); - } - Tracevv((stderr, "inflate: length %u\n", state->length)); - - /* get distance code */ - for (;;) { - this = state->distcode[BITS(state->distbits)]; - if ((unsigned)(this.bits) <= bits) break; - PULLBYTE(); - } - if ((this.op & 0xf0) == 0) { - last = this; - for (;;) { - this = state->distcode[last.val + - (BITS(last.bits + last.op) >> last.bits)]; - if ((unsigned)(last.bits + this.bits) <= bits) break; - PULLBYTE(); - } - DROPBITS(last.bits); - } - DROPBITS(this.bits); - if (this.op & 64) { - strm->msg = (char *)"invalid distance code"; - state->mode = BAD; - break; - } - state->offset = (unsigned)this.val; - - /* get distance extra bits, if any */ - state->extra = (unsigned)(this.op) & 15; - if (state->extra != 0) { - NEEDBITS(state->extra); - state->offset += BITS(state->extra); - DROPBITS(state->extra); - } - if (state->offset > state->wsize - (state->whave < state->wsize ? - left : 0)) { - strm->msg = (char *)"invalid distance too far back"; - state->mode = BAD; - break; - } - Tracevv((stderr, "inflate: distance %u\n", state->offset)); - - /* copy match from window to output */ - do { - ROOM(); - copy = state->wsize - state->offset; - if (copy < left) { - from = put + copy; - copy = left - copy; - } - else { - from = put - state->offset; - copy = left; - } - if (copy > state->length) copy = state->length; - state->length -= copy; - left -= copy; - do { - *put++ = *from++; - } while (--copy); - } while (state->length != 0); - break; - - case DONE: - /* inflate stream terminated properly -- write leftover output */ - ret = Z_STREAM_END; - if (left < state->wsize) { - if (out(out_desc, state->window, state->wsize - left)) - ret = Z_BUF_ERROR; - } - goto inf_leave; - - case BAD: - ret = Z_DATA_ERROR; - goto inf_leave; - - default: /* can't happen, but makes compilers happy */ - ret = Z_STREAM_ERROR; - goto inf_leave; - } - - /* Return unused input */ - inf_leave: - strm->next_in = next; - strm->avail_in = have; - return ret; -} - -int ZEXPORT inflateBackEnd(strm) -z_streamp strm; -{ - if (strm == Z_NULL || strm->state == Z_NULL || strm->zfree == (free_func)0) - return Z_STREAM_ERROR; - ZFREE(strm, strm->state); - strm->state = Z_NULL; - Tracev((stderr, "inflate: end\n")); - return Z_OK; -} diff --git a/sourcepawn/third_party/zlib/inffast.c b/sourcepawn/third_party/zlib/inffast.c deleted file mode 100644 index 20ef523d..00000000 --- a/sourcepawn/third_party/zlib/inffast.c +++ /dev/null @@ -1,319 +0,0 @@ -/* inffast.c -- fast decoding - * Copyright (C) 1995-2004 Mark Adler - * For conditions of distribution and use, see copyright notice in zlib.h - */ - -#include -#include "zutil.h" -#include "inftrees.h" -#include "inflate.h" -#include "inffast.h" - -#ifndef ASMINF - -/* Allow machine dependent optimization for post-increment or pre-increment. - Based on testing to date, - Pre-increment preferred for: - - PowerPC G3 (Adler) - - MIPS R5000 (Randers-Pehrson) - Post-increment preferred for: - - none - No measurable difference: - - Pentium III (Anderson) - - M68060 (Nikl) - */ -#ifdef POSTINC -# define OFF 0 -# define PUP(a) *(a)++ -#else -# define OFF 1 -# define PUP(a) *++(a) -#endif - -/* - Decode literal, length, and distance codes and write out the resulting - literal and match bytes until either not enough input or output is - available, an end-of-block is encountered, or a data error is encountered. - When large enough input and output buffers are supplied to inflate(), for - example, a 16K input buffer and a 64K output buffer, more than 95% of the - inflate execution time is spent in this routine. - - Entry assumptions: - - state->mode == LEN - strm->avail_in >= 6 - strm->avail_out >= 258 - start >= strm->avail_out - state->bits < 8 - - On return, state->mode is one of: - - LEN -- ran out of enough output space or enough available input - TYPE -- reached end of block code, inflate() to interpret next block - BAD -- error in block data - - Notes: - - - The maximum input bits used by a length/distance pair is 15 bits for the - length code, 5 bits for the length extra, 15 bits for the distance code, - and 13 bits for the distance extra. This totals 48 bits, or six bytes. - Therefore if strm->avail_in >= 6, then there is enough input to avoid - checking for available input while decoding. - - - The maximum bytes that a single length/distance pair can output is 258 - bytes, which is the maximum length that can be coded. inflate_fast() - requires strm->avail_out >= 258 for each loop to avoid checking for - output space. - */ -void inflate_fast(strm, start) -z_streamp strm; -unsigned start; /* inflate()'s starting value for strm->avail_out */ -{ - struct inflate_state FAR *state; - unsigned char FAR *in; /* local strm->next_in */ - unsigned char FAR *last; /* while in < last, enough input available */ - unsigned char FAR *out; /* local strm->next_out */ - unsigned char FAR *beg; /* inflate()'s initial strm->next_out */ - unsigned char FAR *end; /* while out < end, enough space available */ -#ifdef INFLATE_STRICT - unsigned dmax; /* maximum distance from zlib header */ -#endif - unsigned wsize; /* window size or zero if not using window */ - unsigned whave; /* valid bytes in the window */ - unsigned write; /* window write index */ - unsigned char FAR *window; /* allocated sliding window, if wsize != 0 */ - unsigned long hold; /* local strm->hold */ - unsigned bits; /* local strm->bits */ - code const FAR *lcode; /* local strm->lencode */ - code const FAR *dcode; /* local strm->distcode */ - unsigned lmask; /* mask for first level of length codes */ - unsigned dmask; /* mask for first level of distance codes */ - code this; /* retrieved table entry */ - unsigned op; /* code bits, operation, extra bits, or */ - /* window position, window bytes to copy */ - unsigned len; /* match length, unused bytes */ - unsigned dist; /* match distance */ - unsigned char FAR *from; /* where to copy match from */ - - /* copy state to local variables */ - state = (struct inflate_state FAR *)strm->state; - in = strm->next_in - OFF; - last = in + (strm->avail_in - 5); - out = strm->next_out - OFF; - beg = out - (start - strm->avail_out); - end = out + (strm->avail_out - 257); -#ifdef INFLATE_STRICT - dmax = state->dmax; -#endif - wsize = state->wsize; - whave = state->whave; - write = state->write; - window = state->window; - hold = state->hold; - bits = state->bits; - lcode = state->lencode; - dcode = state->distcode; - lmask = (1U << state->lenbits) - 1; - dmask = (1U << state->distbits) - 1; - - /* decode literals and length/distances until end-of-block or not enough - input data or output space */ - do { - if (bits < 15) { - hold += (unsigned long)(PUP(in)) << bits; - bits += 8; - hold += (unsigned long)(PUP(in)) << bits; - bits += 8; - } - this = lcode[hold & lmask]; - dolen: - op = (unsigned)(this.bits); - hold >>= op; - bits -= op; - op = (unsigned)(this.op); - if (op == 0) { /* literal */ - Tracevv((stderr, this.val >= 0x20 && this.val < 0x7f ? - "inflate: literal '%c'\n" : - "inflate: literal 0x%02x\n", this.val)); - PUP(out) = (unsigned char)(this.val); - } - else if (op & 16) { /* length base */ - len = (unsigned)(this.val); - op &= 15; /* number of extra bits */ - if (op) { - if (bits < op) { - hold += (unsigned long)(PUP(in)) << bits; - bits += 8; - } - len += (unsigned)hold & ((1U << op) - 1); - hold >>= op; - bits -= op; - } - Tracevv((stderr, "inflate: length %u\n", len)); - if (bits < 15) { - hold += (unsigned long)(PUP(in)) << bits; - bits += 8; - hold += (unsigned long)(PUP(in)) << bits; - bits += 8; - } - this = dcode[hold & dmask]; - dodist: - op = (unsigned)(this.bits); - hold >>= op; - bits -= op; - op = (unsigned)(this.op); - if (op & 16) { /* distance base */ - dist = (unsigned)(this.val); - op &= 15; /* number of extra bits */ - if (bits < op) { - hold += (unsigned long)(PUP(in)) << bits; - bits += 8; - if (bits < op) { - hold += (unsigned long)(PUP(in)) << bits; - bits += 8; - } - } - dist += (unsigned)hold & ((1U << op) - 1); -#ifdef INFLATE_STRICT - if (dist > dmax) { - strm->msg = (char *)"invalid distance too far back"; - state->mode = BAD; - break; - } -#endif - hold >>= op; - bits -= op; - Tracevv((stderr, "inflate: distance %u\n", dist)); - op = (unsigned)(out - beg); /* max distance in output */ - if (dist > op) { /* see if copy from window */ - op = dist - op; /* distance back in window */ - if (op > whave) { - strm->msg = (char *)"invalid distance too far back"; - state->mode = BAD; - break; - } - from = window - OFF; - if (write == 0) { /* very common case */ - from += wsize - op; - if (op < len) { /* some from window */ - len -= op; - do { - PUP(out) = PUP(from); - } while (--op); - from = out - dist; /* rest from output */ - } - } - else if (write < op) { /* wrap around window */ - from += wsize + write - op; - op -= write; - if (op < len) { /* some from end of window */ - len -= op; - do { - PUP(out) = PUP(from); - } while (--op); - from = window - OFF; - if (write < len) { /* some from start of window */ - op = write; - len -= op; - do { - PUP(out) = PUP(from); - } while (--op); - from = out - dist; /* rest from output */ - } - } - } - else { /* contiguous in window */ - from += write - op; - if (op < len) { /* some from window */ - len -= op; - do { - PUP(out) = PUP(from); - } while (--op); - from = out - dist; /* rest from output */ - } - } - while (len > 2) { - PUP(out) = PUP(from); - PUP(out) = PUP(from); - PUP(out) = PUP(from); - len -= 3; - } - if (len) { - PUP(out) = PUP(from); - if (len > 1) - PUP(out) = PUP(from); - } - } - else { - from = out - dist; /* copy direct from output */ - do { /* minimum length is three */ - PUP(out) = PUP(from); - PUP(out) = PUP(from); - PUP(out) = PUP(from); - len -= 3; - } while (len > 2); - if (len) { - PUP(out) = PUP(from); - if (len > 1) - PUP(out) = PUP(from); - } - } - } - else if ((op & 64) == 0) { /* 2nd level distance code */ - this = dcode[this.val + (hold & ((1U << op) - 1))]; - goto dodist; - } - else { - strm->msg = (char *)"invalid distance code"; - state->mode = BAD; - break; - } - } - else if ((op & 64) == 0) { /* 2nd level length code */ - this = lcode[this.val + (hold & ((1U << op) - 1))]; - goto dolen; - } - else if (op & 32) { /* end-of-block */ - Tracevv((stderr, "inflate: end of block\n")); - state->mode = TYPE; - break; - } - else { - strm->msg = (char *)"invalid literal/length code"; - state->mode = BAD; - break; - } - } while (in < last && out < end); - - /* return unused bytes (on entry, bits < 8, so in won't go too far back) */ - len = bits >> 3; - in -= len; - bits -= len << 3; - hold &= (1U << bits) - 1; - - /* update state and return */ - strm->next_in = in + OFF; - strm->next_out = out + OFF; - strm->avail_in = (unsigned)(in < last ? 5 + (last - in) : 5 - (in - last)); - strm->avail_out = (unsigned)(out < end ? - 257 + (end - out) : 257 - (out - end)); - state->hold = hold; - state->bits = bits; - return; -} - -/* - inflate_fast() speedups that turned out slower (on a PowerPC G3 750CXe): - - Using bit fields for code structure - - Different op definition to avoid & for extra bits (do & for table bits) - - Three separate decoding do-loops for direct, window, and write == 0 - - Special case for distance > 1 copies to do overlapped load and store copy - - Explicit branch predictions (based on measured branch probabilities) - - Deferring match copy and interspersed it with decoding subsequent codes - - Swapping literal/length else - - Swapping window/direct else - - Larger unrolled copy loops (three is about right) - - Moving len -= 3 statement into middle of loop - */ - -#endif /* !ASMINF */ diff --git a/sourcepawn/third_party/zlib/inffast.h b/sourcepawn/third_party/zlib/inffast.h deleted file mode 100644 index 614fa787..00000000 --- a/sourcepawn/third_party/zlib/inffast.h +++ /dev/null @@ -1,11 +0,0 @@ -/* inffast.h -- header to use inffast.c - * Copyright (C) 1995-2003 Mark Adler - * For conditions of distribution and use, see copyright notice in zlib.h - */ - -/* WARNING: this file should *not* be used by applications. It is - part of the implementation of the compression library and is - subject to change. Applications should only use zlib.h. - */ - -void inflate_fast OF((z_streamp strm, unsigned start)); diff --git a/sourcepawn/third_party/zlib/inffixed.h b/sourcepawn/third_party/zlib/inffixed.h deleted file mode 100644 index 423d5c5b..00000000 --- a/sourcepawn/third_party/zlib/inffixed.h +++ /dev/null @@ -1,94 +0,0 @@ - /* inffixed.h -- table for decoding fixed codes - * Generated automatically by makefixed(). - */ - - /* WARNING: this file should *not* be used by applications. It - is part of the implementation of the compression library and - is subject to change. Applications should only use zlib.h. - */ - - static const code lenfix[512] = { - {96,7,0},{0,8,80},{0,8,16},{20,8,115},{18,7,31},{0,8,112},{0,8,48}, - {0,9,192},{16,7,10},{0,8,96},{0,8,32},{0,9,160},{0,8,0},{0,8,128}, - {0,8,64},{0,9,224},{16,7,6},{0,8,88},{0,8,24},{0,9,144},{19,7,59}, - {0,8,120},{0,8,56},{0,9,208},{17,7,17},{0,8,104},{0,8,40},{0,9,176}, - {0,8,8},{0,8,136},{0,8,72},{0,9,240},{16,7,4},{0,8,84},{0,8,20}, - {21,8,227},{19,7,43},{0,8,116},{0,8,52},{0,9,200},{17,7,13},{0,8,100}, - {0,8,36},{0,9,168},{0,8,4},{0,8,132},{0,8,68},{0,9,232},{16,7,8}, - {0,8,92},{0,8,28},{0,9,152},{20,7,83},{0,8,124},{0,8,60},{0,9,216}, - {18,7,23},{0,8,108},{0,8,44},{0,9,184},{0,8,12},{0,8,140},{0,8,76}, - {0,9,248},{16,7,3},{0,8,82},{0,8,18},{21,8,163},{19,7,35},{0,8,114}, - {0,8,50},{0,9,196},{17,7,11},{0,8,98},{0,8,34},{0,9,164},{0,8,2}, - {0,8,130},{0,8,66},{0,9,228},{16,7,7},{0,8,90},{0,8,26},{0,9,148}, - {20,7,67},{0,8,122},{0,8,58},{0,9,212},{18,7,19},{0,8,106},{0,8,42}, - {0,9,180},{0,8,10},{0,8,138},{0,8,74},{0,9,244},{16,7,5},{0,8,86}, - {0,8,22},{64,8,0},{19,7,51},{0,8,118},{0,8,54},{0,9,204},{17,7,15}, - {0,8,102},{0,8,38},{0,9,172},{0,8,6},{0,8,134},{0,8,70},{0,9,236}, - {16,7,9},{0,8,94},{0,8,30},{0,9,156},{20,7,99},{0,8,126},{0,8,62}, - {0,9,220},{18,7,27},{0,8,110},{0,8,46},{0,9,188},{0,8,14},{0,8,142}, - {0,8,78},{0,9,252},{96,7,0},{0,8,81},{0,8,17},{21,8,131},{18,7,31}, - {0,8,113},{0,8,49},{0,9,194},{16,7,10},{0,8,97},{0,8,33},{0,9,162}, - {0,8,1},{0,8,129},{0,8,65},{0,9,226},{16,7,6},{0,8,89},{0,8,25}, - {0,9,146},{19,7,59},{0,8,121},{0,8,57},{0,9,210},{17,7,17},{0,8,105}, - {0,8,41},{0,9,178},{0,8,9},{0,8,137},{0,8,73},{0,9,242},{16,7,4}, - {0,8,85},{0,8,21},{16,8,258},{19,7,43},{0,8,117},{0,8,53},{0,9,202}, - {17,7,13},{0,8,101},{0,8,37},{0,9,170},{0,8,5},{0,8,133},{0,8,69}, - {0,9,234},{16,7,8},{0,8,93},{0,8,29},{0,9,154},{20,7,83},{0,8,125}, - {0,8,61},{0,9,218},{18,7,23},{0,8,109},{0,8,45},{0,9,186},{0,8,13}, - {0,8,141},{0,8,77},{0,9,250},{16,7,3},{0,8,83},{0,8,19},{21,8,195}, - {19,7,35},{0,8,115},{0,8,51},{0,9,198},{17,7,11},{0,8,99},{0,8,35}, - {0,9,166},{0,8,3},{0,8,131},{0,8,67},{0,9,230},{16,7,7},{0,8,91}, - {0,8,27},{0,9,150},{20,7,67},{0,8,123},{0,8,59},{0,9,214},{18,7,19}, - {0,8,107},{0,8,43},{0,9,182},{0,8,11},{0,8,139},{0,8,75},{0,9,246}, - {16,7,5},{0,8,87},{0,8,23},{64,8,0},{19,7,51},{0,8,119},{0,8,55}, - {0,9,206},{17,7,15},{0,8,103},{0,8,39},{0,9,174},{0,8,7},{0,8,135}, - {0,8,71},{0,9,238},{16,7,9},{0,8,95},{0,8,31},{0,9,158},{20,7,99}, - {0,8,127},{0,8,63},{0,9,222},{18,7,27},{0,8,111},{0,8,47},{0,9,190}, - {0,8,15},{0,8,143},{0,8,79},{0,9,254},{96,7,0},{0,8,80},{0,8,16}, - {20,8,115},{18,7,31},{0,8,112},{0,8,48},{0,9,193},{16,7,10},{0,8,96}, - {0,8,32},{0,9,161},{0,8,0},{0,8,128},{0,8,64},{0,9,225},{16,7,6}, - {0,8,88},{0,8,24},{0,9,145},{19,7,59},{0,8,120},{0,8,56},{0,9,209}, - {17,7,17},{0,8,104},{0,8,40},{0,9,177},{0,8,8},{0,8,136},{0,8,72}, - {0,9,241},{16,7,4},{0,8,84},{0,8,20},{21,8,227},{19,7,43},{0,8,116}, - {0,8,52},{0,9,201},{17,7,13},{0,8,100},{0,8,36},{0,9,169},{0,8,4}, - {0,8,132},{0,8,68},{0,9,233},{16,7,8},{0,8,92},{0,8,28},{0,9,153}, - {20,7,83},{0,8,124},{0,8,60},{0,9,217},{18,7,23},{0,8,108},{0,8,44}, - {0,9,185},{0,8,12},{0,8,140},{0,8,76},{0,9,249},{16,7,3},{0,8,82}, - {0,8,18},{21,8,163},{19,7,35},{0,8,114},{0,8,50},{0,9,197},{17,7,11}, - {0,8,98},{0,8,34},{0,9,165},{0,8,2},{0,8,130},{0,8,66},{0,9,229}, - {16,7,7},{0,8,90},{0,8,26},{0,9,149},{20,7,67},{0,8,122},{0,8,58}, - {0,9,213},{18,7,19},{0,8,106},{0,8,42},{0,9,181},{0,8,10},{0,8,138}, - {0,8,74},{0,9,245},{16,7,5},{0,8,86},{0,8,22},{64,8,0},{19,7,51}, - {0,8,118},{0,8,54},{0,9,205},{17,7,15},{0,8,102},{0,8,38},{0,9,173}, - {0,8,6},{0,8,134},{0,8,70},{0,9,237},{16,7,9},{0,8,94},{0,8,30}, - {0,9,157},{20,7,99},{0,8,126},{0,8,62},{0,9,221},{18,7,27},{0,8,110}, - {0,8,46},{0,9,189},{0,8,14},{0,8,142},{0,8,78},{0,9,253},{96,7,0}, - {0,8,81},{0,8,17},{21,8,131},{18,7,31},{0,8,113},{0,8,49},{0,9,195}, - {16,7,10},{0,8,97},{0,8,33},{0,9,163},{0,8,1},{0,8,129},{0,8,65}, - {0,9,227},{16,7,6},{0,8,89},{0,8,25},{0,9,147},{19,7,59},{0,8,121}, - {0,8,57},{0,9,211},{17,7,17},{0,8,105},{0,8,41},{0,9,179},{0,8,9}, - {0,8,137},{0,8,73},{0,9,243},{16,7,4},{0,8,85},{0,8,21},{16,8,258}, - {19,7,43},{0,8,117},{0,8,53},{0,9,203},{17,7,13},{0,8,101},{0,8,37}, - {0,9,171},{0,8,5},{0,8,133},{0,8,69},{0,9,235},{16,7,8},{0,8,93}, - {0,8,29},{0,9,155},{20,7,83},{0,8,125},{0,8,61},{0,9,219},{18,7,23}, - {0,8,109},{0,8,45},{0,9,187},{0,8,13},{0,8,141},{0,8,77},{0,9,251}, - {16,7,3},{0,8,83},{0,8,19},{21,8,195},{19,7,35},{0,8,115},{0,8,51}, - {0,9,199},{17,7,11},{0,8,99},{0,8,35},{0,9,167},{0,8,3},{0,8,131}, - {0,8,67},{0,9,231},{16,7,7},{0,8,91},{0,8,27},{0,9,151},{20,7,67}, - {0,8,123},{0,8,59},{0,9,215},{18,7,19},{0,8,107},{0,8,43},{0,9,183}, - {0,8,11},{0,8,139},{0,8,75},{0,9,247},{16,7,5},{0,8,87},{0,8,23}, - {64,8,0},{19,7,51},{0,8,119},{0,8,55},{0,9,207},{17,7,15},{0,8,103}, - {0,8,39},{0,9,175},{0,8,7},{0,8,135},{0,8,71},{0,9,239},{16,7,9}, - {0,8,95},{0,8,31},{0,9,159},{20,7,99},{0,8,127},{0,8,63},{0,9,223}, - {18,7,27},{0,8,111},{0,8,47},{0,9,191},{0,8,15},{0,8,143},{0,8,79}, - {0,9,255} - }; - - static const code distfix[32] = { - {16,5,1},{23,5,257},{19,5,17},{27,5,4097},{17,5,5},{25,5,1025}, - {21,5,65},{29,5,16385},{16,5,3},{24,5,513},{20,5,33},{28,5,8193}, - {18,5,9},{26,5,2049},{22,5,129},{64,5,0},{16,5,2},{23,5,385}, - {19,5,25},{27,5,6145},{17,5,7},{25,5,1537},{21,5,97},{29,5,24577}, - {16,5,4},{24,5,769},{20,5,49},{28,5,12289},{18,5,13},{26,5,3073}, - {22,5,193},{64,5,0} - }; diff --git a/sourcepawn/third_party/zlib/inflate.c b/sourcepawn/third_party/zlib/inflate.c deleted file mode 100644 index f4606b62..00000000 --- a/sourcepawn/third_party/zlib/inflate.c +++ /dev/null @@ -1,1369 +0,0 @@ -/* inflate.c -- zlib decompression - * Copyright (C) 1995-2005 Mark Adler - * For conditions of distribution and use, see copyright notice in zlib.h - */ - -/* - * Change history: - * - * 1.2.beta0 24 Nov 2002 - * - First version -- complete rewrite of inflate to simplify code, avoid - * creation of window when not needed, minimize use of window when it is - * needed, make inffast.c even faster, implement gzip decoding, and to - * improve code readability and style over the previous zlib inflate code - * - * 1.2.beta1 25 Nov 2002 - * - Use pointers for available input and output checking in inffast.c - * - Remove input and output counters in inffast.c - * - Change inffast.c entry and loop from avail_in >= 7 to >= 6 - * - Remove unnecessary second byte pull from length extra in inffast.c - * - Unroll direct copy to three copies per loop in inffast.c - * - * 1.2.beta2 4 Dec 2002 - * - Change external routine names to reduce potential conflicts - * - Correct filename to inffixed.h for fixed tables in inflate.c - * - Make hbuf[] unsigned char to match parameter type in inflate.c - * - Change strm->next_out[-state->offset] to *(strm->next_out - state->offset) - * to avoid negation problem on Alphas (64 bit) in inflate.c - * - * 1.2.beta3 22 Dec 2002 - * - Add comments on state->bits assertion in inffast.c - * - Add comments on op field in inftrees.h - * - Fix bug in reuse of allocated window after inflateReset() - * - Remove bit fields--back to byte structure for speed - * - Remove distance extra == 0 check in inflate_fast()--only helps for lengths - * - Change post-increments to pre-increments in inflate_fast(), PPC biased? - * - Add compile time option, POSTINC, to use post-increments instead (Intel?) - * - Make MATCH copy in inflate() much faster for when inflate_fast() not used - * - Use local copies of stream next and avail values, as well as local bit - * buffer and bit count in inflate()--for speed when inflate_fast() not used - * - * 1.2.beta4 1 Jan 2003 - * - Split ptr - 257 statements in inflate_table() to avoid compiler warnings - * - Move a comment on output buffer sizes from inffast.c to inflate.c - * - Add comments in inffast.c to introduce the inflate_fast() routine - * - Rearrange window copies in inflate_fast() for speed and simplification - * - Unroll last copy for window match in inflate_fast() - * - Use local copies of window variables in inflate_fast() for speed - * - Pull out common write == 0 case for speed in inflate_fast() - * - Make op and len in inflate_fast() unsigned for consistency - * - Add FAR to lcode and dcode declarations in inflate_fast() - * - Simplified bad distance check in inflate_fast() - * - Added inflateBackInit(), inflateBack(), and inflateBackEnd() in new - * source file infback.c to provide a call-back interface to inflate for - * programs like gzip and unzip -- uses window as output buffer to avoid - * window copying - * - * 1.2.beta5 1 Jan 2003 - * - Improved inflateBack() interface to allow the caller to provide initial - * input in strm. - * - Fixed stored blocks bug in inflateBack() - * - * 1.2.beta6 4 Jan 2003 - * - Added comments in inffast.c on effectiveness of POSTINC - * - Typecasting all around to reduce compiler warnings - * - Changed loops from while (1) or do {} while (1) to for (;;), again to - * make compilers happy - * - Changed type of window in inflateBackInit() to unsigned char * - * - * 1.2.beta7 27 Jan 2003 - * - Changed many types to unsigned or unsigned short to avoid warnings - * - Added inflateCopy() function - * - * 1.2.0 9 Mar 2003 - * - Changed inflateBack() interface to provide separate opaque descriptors - * for the in() and out() functions - * - Changed inflateBack() argument and in_func typedef to swap the length - * and buffer address return values for the input function - * - Check next_in and next_out for Z_NULL on entry to inflate() - * - * The history for versions after 1.2.0 are in ChangeLog in zlib distribution. - */ - -#include -#include "zutil.h" -#include "inftrees.h" -#include "inflate.h" -#include "inffast.h" - -#ifdef MAKEFIXED -# ifndef BUILDFIXED -# define BUILDFIXED -# endif -#endif - -/* function prototypes */ -local void fixedtables OF((struct inflate_state FAR *state)); -local int updatewindow OF((z_streamp strm, unsigned out)); -#ifdef BUILDFIXED - void makefixed OF((void)); -#endif -local unsigned syncsearch OF((unsigned FAR *have, unsigned char FAR *buf, - unsigned len)); - -int ZEXPORT inflateReset(strm) -z_streamp strm; -{ - struct inflate_state FAR *state; - - if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; - state = (struct inflate_state FAR *)strm->state; - strm->total_in = strm->total_out = state->total = 0; - strm->msg = Z_NULL; - strm->adler = 1; /* to support ill-conceived Java test suite */ - state->mode = HEAD; - state->last = 0; - state->havedict = 0; - state->dmax = 32768U; - state->head = Z_NULL; - state->wsize = 0; - state->whave = 0; - state->write = 0; - state->hold = 0; - state->bits = 0; - state->lencode = state->distcode = state->next = state->codes; - Tracev((stderr, "inflate: reset\n")); - return Z_OK; -} - -int ZEXPORT inflatePrime(strm, bits, value) -z_streamp strm; -int bits; -int value; -{ - struct inflate_state FAR *state; - - if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; - state = (struct inflate_state FAR *)strm->state; - if (bits > 16 || state->bits + bits > 32) return Z_STREAM_ERROR; - value &= (1L << bits) - 1; - state->hold += value << state->bits; - state->bits += bits; - return Z_OK; -} - -int ZEXPORT inflateInit2_(strm, windowBits, version, stream_size) -z_streamp strm; -int windowBits; -const char *version; -int stream_size; -{ - struct inflate_state FAR *state; - - if (version == Z_NULL || version[0] != ZLIB_VERSION[0] || - stream_size != (int)(sizeof(z_stream))) - return Z_VERSION_ERROR; - if (strm == Z_NULL) return Z_STREAM_ERROR; - strm->msg = Z_NULL; /* in case we return an error */ - if (strm->zalloc == (alloc_func)0) { - strm->zalloc = zcalloc; - strm->opaque = (voidpf)0; - } - if (strm->zfree == (free_func)0) strm->zfree = zcfree; - state = (struct inflate_state FAR *) - ZALLOC(strm, 1, sizeof(struct inflate_state)); - if (state == Z_NULL) return Z_MEM_ERROR; - Tracev((stderr, "inflate: allocated\n")); - strm->state = (struct internal_state FAR *)state; - if (windowBits < 0) { - state->wrap = 0; - windowBits = -windowBits; - } - else { - state->wrap = (windowBits >> 4) + 1; -#ifdef GUNZIP - if (windowBits < 48) windowBits &= 15; -#endif - } - if (windowBits < 8 || windowBits > 15) { - ZFREE(strm, state); - strm->state = Z_NULL; - return Z_STREAM_ERROR; - } - state->wbits = (unsigned)windowBits; - state->window = Z_NULL; - return inflateReset(strm); -} - -int ZEXPORT inflateInit_(strm, version, stream_size) -z_streamp strm; -const char *version; -int stream_size; -{ - return inflateInit2_(strm, DEF_WBITS, version, stream_size); -} - -/* - Return state with length and distance decoding tables and index sizes set to - fixed code decoding. Normally this returns fixed tables from inffixed.h. - If BUILDFIXED is defined, then instead this routine builds the tables the - first time it's called, and returns those tables the first time and - thereafter. This reduces the size of the code by about 2K bytes, in - exchange for a little execution time. However, BUILDFIXED should not be - used for threaded applications, since the rewriting of the tables and virgin - may not be thread-safe. - */ -local void fixedtables(state) -struct inflate_state FAR *state; -{ -#ifdef BUILDFIXED - static int virgin = 1; - static code *lenfix, *distfix; - static code fixed[544]; - - /* build fixed huffman tables if first call (may not be thread safe) */ - if (virgin) { - unsigned sym, bits; - static code *next; - - /* literal/length table */ - sym = 0; - while (sym < 144) state->lens[sym++] = 8; - while (sym < 256) state->lens[sym++] = 9; - while (sym < 280) state->lens[sym++] = 7; - while (sym < 288) state->lens[sym++] = 8; - next = fixed; - lenfix = next; - bits = 9; - inflate_table(LENS, state->lens, 288, &(next), &(bits), state->work); - - /* distance table */ - sym = 0; - while (sym < 32) state->lens[sym++] = 5; - distfix = next; - bits = 5; - inflate_table(DISTS, state->lens, 32, &(next), &(bits), state->work); - - /* do this just once */ - virgin = 0; - } -#else /* !BUILDFIXED */ -# include "inffixed.h" -#endif /* BUILDFIXED */ - state->lencode = lenfix; - state->lenbits = 9; - state->distcode = distfix; - state->distbits = 5; -} - -#ifdef MAKEFIXED -#include - -/* - Write out the inffixed.h that is #include'd above. Defining MAKEFIXED also - defines BUILDFIXED, so the tables are built on the fly. makefixed() writes - those tables to stdout, which would be piped to inffixed.h. A small program - can simply call makefixed to do this: - - void makefixed(void); - - int main(void) - { - makefixed(); - return 0; - } - - Then that can be linked with zlib built with MAKEFIXED defined and run: - - a.out > inffixed.h - */ -void makefixed() -{ - unsigned low, size; - struct inflate_state state; - - fixedtables(&state); - puts(" /* inffixed.h -- table for decoding fixed codes"); - puts(" * Generated automatically by makefixed()."); - puts(" */"); - puts(""); - puts(" /* WARNING: this file should *not* be used by applications."); - puts(" It is part of the implementation of this library and is"); - puts(" subject to change. Applications should only use zlib.h."); - puts(" */"); - puts(""); - size = 1U << 9; - printf(" static const code lenfix[%u] = {", size); - low = 0; - for (;;) { - if ((low % 7) == 0) printf("\n "); - printf("{%u,%u,%d}", state.lencode[low].op, state.lencode[low].bits, - state.lencode[low].val); - if (++low == size) break; - putchar(','); - } - puts("\n };"); - size = 1U << 5; - printf("\n static const code distfix[%u] = {", size); - low = 0; - for (;;) { - if ((low % 6) == 0) printf("\n "); - printf("{%u,%u,%d}", state.distcode[low].op, state.distcode[low].bits, - state.distcode[low].val); - if (++low == size) break; - putchar(','); - } - puts("\n };"); -} -#endif /* MAKEFIXED */ - -/* - Update the window with the last wsize (normally 32K) bytes written before - returning. If window does not exist yet, create it. This is only called - when a window is already in use, or when output has been written during this - inflate call, but the end of the deflate stream has not been reached yet. - It is also called to create a window for dictionary data when a dictionary - is loaded. - - Providing output buffers larger than 32K to inflate() should provide a speed - advantage, since only the last 32K of output is copied to the sliding window - upon return from inflate(), and since all distances after the first 32K of - output will fall in the output data, making match copies simpler and faster. - The advantage may be dependent on the size of the processor's data caches. - */ -local int updatewindow(strm, out) -z_streamp strm; -unsigned out; -{ - struct inflate_state FAR *state; - unsigned copy, dist; - - state = (struct inflate_state FAR *)strm->state; - - /* if it hasn't been done already, allocate space for the window */ - if (state->window == Z_NULL) { - state->window = (unsigned char FAR *) - ZALLOC(strm, 1U << state->wbits, - sizeof(unsigned char)); - if (state->window == Z_NULL) return 1; - } - - /* if window not in use yet, initialize */ - if (state->wsize == 0) { - state->wsize = 1U << state->wbits; - state->write = 0; - state->whave = 0; - } - - /* copy state->wsize or less output bytes into the circular window */ - copy = out - strm->avail_out; - if (copy >= state->wsize) { - zmemcpy(state->window, strm->next_out - state->wsize, state->wsize); - state->write = 0; - state->whave = state->wsize; - } - else { - dist = state->wsize - state->write; - if (dist > copy) dist = copy; - zmemcpy(state->window + state->write, strm->next_out - copy, dist); - copy -= dist; - if (copy) { - zmemcpy(state->window, strm->next_out - copy, copy); - state->write = copy; - state->whave = state->wsize; - } - else { - state->write += dist; - if (state->write == state->wsize) state->write = 0; - if (state->whave < state->wsize) state->whave += dist; - } - } - return 0; -} - -/* Macros for inflate(): */ - -/* check function to use adler32() for zlib or crc32() for gzip */ -#ifdef GUNZIP -# define UPDATE(check, buf, len) \ - (state->flags ? crc32(check, buf, len) : adler32(check, buf, len)) -#else -# define UPDATE(check, buf, len) adler32(check, buf, len) -#endif - -/* check macros for header crc */ -#ifdef GUNZIP -# define CRC2(check, word) \ - do { \ - hbuf[0] = (unsigned char)(word); \ - hbuf[1] = (unsigned char)((word) >> 8); \ - check = crc32(check, hbuf, 2); \ - } while (0) - -# define CRC4(check, word) \ - do { \ - hbuf[0] = (unsigned char)(word); \ - hbuf[1] = (unsigned char)((word) >> 8); \ - hbuf[2] = (unsigned char)((word) >> 16); \ - hbuf[3] = (unsigned char)((word) >> 24); \ - check = crc32(check, hbuf, 4); \ - } while (0) -#endif - -/* Load registers with state in inflate() for speed */ -#define LOAD() \ - do { \ - put = strm->next_out; \ - left = strm->avail_out; \ - next = strm->next_in; \ - have = strm->avail_in; \ - hold = state->hold; \ - bits = state->bits; \ - } while (0) - -/* Restore state from registers in inflate() */ -#define RESTORE() \ - do { \ - strm->next_out = put; \ - strm->avail_out = left; \ - strm->next_in = next; \ - strm->avail_in = have; \ - state->hold = hold; \ - state->bits = bits; \ - } while (0) - -/* Clear the input bit accumulator */ -#define INITBITS() \ - do { \ - hold = 0; \ - bits = 0; \ - } while (0) - -/* Get a byte of input into the bit accumulator, or return from inflate() - if there is no input available. */ -#define PULLBYTE() \ - do { \ - if (have == 0) goto inf_leave; \ - have--; \ - hold += (unsigned long)(*next++) << bits; \ - bits += 8; \ - } while (0) - -/* Assure that there are at least n bits in the bit accumulator. If there is - not enough available input to do that, then return from inflate(). */ -#define NEEDBITS(n) \ - do { \ - while (bits < (unsigned)(n)) \ - PULLBYTE(); \ - } while (0) - -/* Return the low n bits of the bit accumulator (n < 16) */ -#define BITS(n) \ - ((unsigned)hold & ((1U << (n)) - 1)) - -/* Remove n bits from the bit accumulator */ -#define DROPBITS(n) \ - do { \ - hold >>= (n); \ - bits -= (unsigned)(n); \ - } while (0) - -/* Remove zero to seven bits as needed to go to a byte boundary */ -#define BYTEBITS() \ - do { \ - hold >>= bits & 7; \ - bits -= bits & 7; \ - } while (0) - -/* Reverse the bytes in a 32-bit value */ -#define REVERSE(q) \ - ((((q) >> 24) & 0xff) + (((q) >> 8) & 0xff00) + \ - (((q) & 0xff00) << 8) + (((q) & 0xff) << 24)) - -/* - inflate() uses a state machine to process as much input data and generate as - much output data as possible before returning. The state machine is - structured roughly as follows: - - for (;;) switch (state) { - ... - case STATEn: - if (not enough input data or output space to make progress) - return; - ... make progress ... - state = STATEm; - break; - ... - } - - so when inflate() is called again, the same case is attempted again, and - if the appropriate resources are provided, the machine proceeds to the - next state. The NEEDBITS() macro is usually the way the state evaluates - whether it can proceed or should return. NEEDBITS() does the return if - the requested bits are not available. The typical use of the BITS macros - is: - - NEEDBITS(n); - ... do something with BITS(n) ... - DROPBITS(n); - - where NEEDBITS(n) either returns from inflate() if there isn't enough - input left to load n bits into the accumulator, or it continues. BITS(n) - gives the low n bits in the accumulator. When done, DROPBITS(n) drops - the low n bits off the accumulator. INITBITS() clears the accumulator - and sets the number of available bits to zero. BYTEBITS() discards just - enough bits to put the accumulator on a byte boundary. After BYTEBITS() - and a NEEDBITS(8), then BITS(8) would return the next byte in the stream. - - NEEDBITS(n) uses PULLBYTE() to get an available byte of input, or to return - if there is no input available. The decoding of variable length codes uses - PULLBYTE() directly in order to pull just enough bytes to decode the next - code, and no more. - - Some states loop until they get enough input, making sure that enough - state information is maintained to continue the loop where it left off - if NEEDBITS() returns in the loop. For example, want, need, and keep - would all have to actually be part of the saved state in case NEEDBITS() - returns: - - case STATEw: - while (want < need) { - NEEDBITS(n); - keep[want++] = BITS(n); - DROPBITS(n); - } - state = STATEx; - case STATEx: - - As shown above, if the next state is also the next case, then the break - is omitted. - - A state may also return if there is not enough output space available to - complete that state. Those states are copying stored data, writing a - literal byte, and copying a matching string. - - When returning, a "goto inf_leave" is used to update the total counters, - update the check value, and determine whether any progress has been made - during that inflate() call in order to return the proper return code. - Progress is defined as a change in either strm->avail_in or strm->avail_out. - When there is a window, goto inf_leave will update the window with the last - output written. If a goto inf_leave occurs in the middle of decompression - and there is no window currently, goto inf_leave will create one and copy - output to the window for the next call of inflate(). - - In this implementation, the flush parameter of inflate() only affects the - return code (per zlib.h). inflate() always writes as much as possible to - strm->next_out, given the space available and the provided input--the effect - documented in zlib.h of Z_SYNC_FLUSH. Furthermore, inflate() always defers - the allocation of and copying into a sliding window until necessary, which - provides the effect documented in zlib.h for Z_FINISH when the entire input - stream available. So the only thing the flush parameter actually does is: - when flush is set to Z_FINISH, inflate() cannot return Z_OK. Instead it - will return Z_BUF_ERROR if it has not reached the end of the stream. - */ - -int ZEXPORT inflate(strm, flush) -z_streamp strm; -int flush; -{ - struct inflate_state FAR *state; - unsigned char FAR *next; /* next input */ - unsigned char FAR *put; /* next output */ - unsigned have, left; /* available input and output */ - unsigned long hold; /* bit buffer */ - unsigned bits; /* bits in bit buffer */ - unsigned in, out; /* save starting available input and output */ - unsigned copy; /* number of stored or match bytes to copy */ - unsigned char FAR *from; /* where to copy match bytes from */ - code this; /* current decoding table entry */ - code last; /* parent table entry */ - unsigned len; /* length to copy for repeats, bits to drop */ - int ret; /* return code */ -#ifdef GUNZIP - unsigned char hbuf[4]; /* buffer for gzip header crc calculation */ -#endif - static const unsigned short order[19] = /* permutation of code lengths */ - {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15}; - - if (strm == Z_NULL || strm->state == Z_NULL || strm->next_out == Z_NULL || - (strm->next_in == Z_NULL && strm->avail_in != 0)) - return Z_STREAM_ERROR; - - state = (struct inflate_state FAR *)strm->state; - if (state->mode == TYPE) state->mode = TYPEDO; /* skip check */ - LOAD(); - in = have; - out = left; - ret = Z_OK; - for (;;) - switch (state->mode) { - case HEAD: - if (state->wrap == 0) { - state->mode = TYPEDO; - break; - } - NEEDBITS(16); -#ifdef GUNZIP - if ((state->wrap & 2) && hold == 0x8b1f) { /* gzip header */ - state->check = crc32(0L, Z_NULL, 0); - CRC2(state->check, hold); - INITBITS(); - state->mode = FLAGS; - break; - } - state->flags = 0; /* expect zlib header */ - if (state->head != Z_NULL) - state->head->done = -1; - if (!(state->wrap & 1) || /* check if zlib header allowed */ -#else - if ( -#endif - ((BITS(8) << 8) + (hold >> 8)) % 31) { - strm->msg = (char *)"incorrect header check"; - state->mode = BAD; - break; - } - if (BITS(4) != Z_DEFLATED) { - strm->msg = (char *)"unknown compression method"; - state->mode = BAD; - break; - } - DROPBITS(4); - len = BITS(4) + 8; - if (len > state->wbits) { - strm->msg = (char *)"invalid window size"; - state->mode = BAD; - break; - } - state->dmax = 1U << len; - Tracev((stderr, "inflate: zlib header ok\n")); - strm->adler = state->check = adler32(0L, Z_NULL, 0); - state->mode = hold & 0x200 ? DICTID : TYPE; - INITBITS(); - break; -#ifdef GUNZIP - case FLAGS: - NEEDBITS(16); - state->flags = (int)(hold); - if ((state->flags & 0xff) != Z_DEFLATED) { - strm->msg = (char *)"unknown compression method"; - state->mode = BAD; - break; - } - if (state->flags & 0xe000) { - strm->msg = (char *)"unknown header flags set"; - state->mode = BAD; - break; - } - if (state->head != Z_NULL) - state->head->text = (int)((hold >> 8) & 1); - if (state->flags & 0x0200) CRC2(state->check, hold); - INITBITS(); - state->mode = TIME; - case TIME: - NEEDBITS(32); - if (state->head != Z_NULL) - state->head->time = hold; - if (state->flags & 0x0200) CRC4(state->check, hold); - INITBITS(); - state->mode = OS; - case OS: - NEEDBITS(16); - if (state->head != Z_NULL) { - state->head->xflags = (int)(hold & 0xff); - state->head->os = (int)(hold >> 8); - } - if (state->flags & 0x0200) CRC2(state->check, hold); - INITBITS(); - state->mode = EXLEN; - case EXLEN: - if (state->flags & 0x0400) { - NEEDBITS(16); - state->length = (unsigned)(hold); - if (state->head != Z_NULL) - state->head->extra_len = (unsigned)hold; - if (state->flags & 0x0200) CRC2(state->check, hold); - INITBITS(); - } - else if (state->head != Z_NULL) - state->head->extra = Z_NULL; - state->mode = EXTRA; - case EXTRA: - if (state->flags & 0x0400) { - copy = state->length; - if (copy > have) copy = have; - if (copy) { - if (state->head != Z_NULL && - state->head->extra != Z_NULL) { - len = state->head->extra_len - state->length; - zmemcpy(state->head->extra + len, next, - len + copy > state->head->extra_max ? - state->head->extra_max - len : copy); - } - if (state->flags & 0x0200) - state->check = crc32(state->check, next, copy); - have -= copy; - next += copy; - state->length -= copy; - } - if (state->length) goto inf_leave; - } - state->length = 0; - state->mode = NAME; - case NAME: - if (state->flags & 0x0800) { - if (have == 0) goto inf_leave; - copy = 0; - do { - len = (unsigned)(next[copy++]); - if (state->head != Z_NULL && - state->head->name != Z_NULL && - state->length < state->head->name_max) - state->head->name[state->length++] = len; - } while (len && copy < have); - if (state->flags & 0x0200) - state->check = crc32(state->check, next, copy); - have -= copy; - next += copy; - if (len) goto inf_leave; - } - else if (state->head != Z_NULL) - state->head->name = Z_NULL; - state->length = 0; - state->mode = COMMENT; - case COMMENT: - if (state->flags & 0x1000) { - if (have == 0) goto inf_leave; - copy = 0; - do { - len = (unsigned)(next[copy++]); - if (state->head != Z_NULL && - state->head->comment != Z_NULL && - state->length < state->head->comm_max) - state->head->comment[state->length++] = len; - } while (len && copy < have); - if (state->flags & 0x0200) - state->check = crc32(state->check, next, copy); - have -= copy; - next += copy; - if (len) goto inf_leave; - } - else if (state->head != Z_NULL) - state->head->comment = Z_NULL; - state->mode = HCRC; - case HCRC: - if (state->flags & 0x0200) { - NEEDBITS(16); - if (hold != (state->check & 0xffff)) { - strm->msg = (char *)"header crc mismatch"; - state->mode = BAD; - break; - } - INITBITS(); - } - if (state->head != Z_NULL) { - state->head->hcrc = (int)((state->flags >> 9) & 1); - state->head->done = 1; - } - strm->adler = state->check = crc32(0L, Z_NULL, 0); - state->mode = TYPE; - break; -#endif - case DICTID: - NEEDBITS(32); - strm->adler = state->check = REVERSE(hold); - INITBITS(); - state->mode = DICT; - case DICT: - if (state->havedict == 0) { - RESTORE(); - return Z_NEED_DICT; - } - strm->adler = state->check = adler32(0L, Z_NULL, 0); - state->mode = TYPE; - case TYPE: - if (flush == Z_BLOCK) goto inf_leave; - case TYPEDO: - if (state->last) { - BYTEBITS(); - state->mode = CHECK; - break; - } - NEEDBITS(3); - state->last = BITS(1); - DROPBITS(1); - switch (BITS(2)) { - case 0: /* stored block */ - Tracev((stderr, "inflate: stored block%s\n", - state->last ? " (last)" : "")); - state->mode = STORED; - break; - case 1: /* fixed block */ - fixedtables(state); - Tracev((stderr, "inflate: fixed codes block%s\n", - state->last ? " (last)" : "")); - state->mode = LEN; /* decode codes */ - break; - case 2: /* dynamic block */ - Tracev((stderr, "inflate: dynamic codes block%s\n", - state->last ? " (last)" : "")); - state->mode = TABLE; - break; - case 3: - strm->msg = (char *)"invalid block type"; - state->mode = BAD; - } - DROPBITS(2); - break; - case STORED: - BYTEBITS(); /* go to byte boundary */ - NEEDBITS(32); - if ((hold & 0xffff) != ((hold >> 16) ^ 0xffff)) { - strm->msg = (char *)"invalid stored block lengths"; - state->mode = BAD; - break; - } - state->length = (unsigned)hold & 0xffff; - Tracev((stderr, "inflate: stored length %u\n", - state->length)); - INITBITS(); - state->mode = COPY; - case COPY: - copy = state->length; - if (copy) { - if (copy > have) copy = have; - if (copy > left) copy = left; - if (copy == 0) goto inf_leave; - zmemcpy(put, next, copy); - have -= copy; - next += copy; - left -= copy; - put += copy; - state->length -= copy; - break; - } - Tracev((stderr, "inflate: stored end\n")); - state->mode = TYPE; - break; - case TABLE: - NEEDBITS(14); - state->nlen = BITS(5) + 257; - DROPBITS(5); - state->ndist = BITS(5) + 1; - DROPBITS(5); - state->ncode = BITS(4) + 4; - DROPBITS(4); -#ifndef PKZIP_BUG_WORKAROUND - if (state->nlen > 286 || state->ndist > 30) { - strm->msg = (char *)"too many length or distance symbols"; - state->mode = BAD; - break; - } -#endif - Tracev((stderr, "inflate: table sizes ok\n")); - state->have = 0; - state->mode = LENLENS; - case LENLENS: - while (state->have < state->ncode) { - NEEDBITS(3); - state->lens[order[state->have++]] = (unsigned short)BITS(3); - DROPBITS(3); - } - while (state->have < 19) - state->lens[order[state->have++]] = 0; - state->next = state->codes; - state->lencode = (code const FAR *)(state->next); - state->lenbits = 7; - ret = inflate_table(CODES, state->lens, 19, &(state->next), - &(state->lenbits), state->work); - if (ret) { - strm->msg = (char *)"invalid code lengths set"; - state->mode = BAD; - break; - } - Tracev((stderr, "inflate: code lengths ok\n")); - state->have = 0; - state->mode = CODELENS; - case CODELENS: - while (state->have < state->nlen + state->ndist) { - for (;;) { - this = state->lencode[BITS(state->lenbits)]; - if ((unsigned)(this.bits) <= bits) break; - PULLBYTE(); - } - if (this.val < 16) { - NEEDBITS(this.bits); - DROPBITS(this.bits); - state->lens[state->have++] = this.val; - } - else { - if (this.val == 16) { - NEEDBITS(this.bits + 2); - DROPBITS(this.bits); - if (state->have == 0) { - strm->msg = (char *)"invalid bit length repeat"; - state->mode = BAD; - break; - } - len = state->lens[state->have - 1]; - copy = 3 + BITS(2); - DROPBITS(2); - } - else if (this.val == 17) { - NEEDBITS(this.bits + 3); - DROPBITS(this.bits); - len = 0; - copy = 3 + BITS(3); - DROPBITS(3); - } - else { - NEEDBITS(this.bits + 7); - DROPBITS(this.bits); - len = 0; - copy = 11 + BITS(7); - DROPBITS(7); - } - if (state->have + copy > state->nlen + state->ndist) { - strm->msg = (char *)"invalid bit length repeat"; - state->mode = BAD; - break; - } - while (copy--) - state->lens[state->have++] = (unsigned short)len; - } - } - - /* handle error breaks in while */ - if (state->mode == BAD) break; - - /* build code tables */ - state->next = state->codes; - state->lencode = (code const FAR *)(state->next); - state->lenbits = 9; - ret = inflate_table(LENS, state->lens, state->nlen, &(state->next), - &(state->lenbits), state->work); - if (ret) { - strm->msg = (char *)"invalid literal/lengths set"; - state->mode = BAD; - break; - } - state->distcode = (code const FAR *)(state->next); - state->distbits = 6; - ret = inflate_table(DISTS, state->lens + state->nlen, state->ndist, - &(state->next), &(state->distbits), state->work); - if (ret) { - strm->msg = (char *)"invalid distances set"; - state->mode = BAD; - break; - } - Tracev((stderr, "inflate: codes ok\n")); - state->mode = LEN; - case LEN: - if (have >= 6 && left >= 258) { - RESTORE(); - inflate_fast(strm, out); - LOAD(); - break; - } - for (;;) { - this = state->lencode[BITS(state->lenbits)]; - if ((unsigned)(this.bits) <= bits) break; - PULLBYTE(); - } - if (this.op && (this.op & 0xf0) == 0) { - last = this; - for (;;) { - this = state->lencode[last.val + - (BITS(last.bits + last.op) >> last.bits)]; - if ((unsigned)(last.bits + this.bits) <= bits) break; - PULLBYTE(); - } - DROPBITS(last.bits); - } - DROPBITS(this.bits); - state->length = (unsigned)this.val; - if ((int)(this.op) == 0) { - Tracevv((stderr, this.val >= 0x20 && this.val < 0x7f ? - "inflate: literal '%c'\n" : - "inflate: literal 0x%02x\n", this.val)); - state->mode = LIT; - break; - } - if (this.op & 32) { - Tracevv((stderr, "inflate: end of block\n")); - state->mode = TYPE; - break; - } - if (this.op & 64) { - strm->msg = (char *)"invalid literal/length code"; - state->mode = BAD; - break; - } - state->extra = (unsigned)(this.op) & 15; - state->mode = LENEXT; - case LENEXT: - if (state->extra) { - NEEDBITS(state->extra); - state->length += BITS(state->extra); - DROPBITS(state->extra); - } - Tracevv((stderr, "inflate: length %u\n", state->length)); - state->mode = DIST; - case DIST: - for (;;) { - this = state->distcode[BITS(state->distbits)]; - if ((unsigned)(this.bits) <= bits) break; - PULLBYTE(); - } - if ((this.op & 0xf0) == 0) { - last = this; - for (;;) { - this = state->distcode[last.val + - (BITS(last.bits + last.op) >> last.bits)]; - if ((unsigned)(last.bits + this.bits) <= bits) break; - PULLBYTE(); - } - DROPBITS(last.bits); - } - DROPBITS(this.bits); - if (this.op & 64) { - strm->msg = (char *)"invalid distance code"; - state->mode = BAD; - break; - } - state->offset = (unsigned)this.val; - state->extra = (unsigned)(this.op) & 15; - state->mode = DISTEXT; - case DISTEXT: - if (state->extra) { - NEEDBITS(state->extra); - state->offset += BITS(state->extra); - DROPBITS(state->extra); - } -#ifdef INFLATE_STRICT - if (state->offset > state->dmax) { - strm->msg = (char *)"invalid distance too far back"; - state->mode = BAD; - break; - } -#endif - if (state->offset > state->whave + out - left) { - strm->msg = (char *)"invalid distance too far back"; - state->mode = BAD; - break; - } - Tracevv((stderr, "inflate: distance %u\n", state->offset)); - state->mode = MATCH; - case MATCH: - if (left == 0) goto inf_leave; - copy = out - left; - if (state->offset > copy) { /* copy from window */ - copy = state->offset - copy; - if (copy > state->write) { - copy -= state->write; - from = state->window + (state->wsize - copy); - } - else - from = state->window + (state->write - copy); - if (copy > state->length) copy = state->length; - } - else { /* copy from output */ - from = put - state->offset; - copy = state->length; - } - if (copy > left) copy = left; - left -= copy; - state->length -= copy; - do { - *put++ = *from++; - } while (--copy); - if (state->length == 0) state->mode = LEN; - break; - case LIT: - if (left == 0) goto inf_leave; - *put++ = (unsigned char)(state->length); - left--; - state->mode = LEN; - break; - case CHECK: - if (state->wrap) { - NEEDBITS(32); - out -= left; - strm->total_out += out; - state->total += out; - if (out) - strm->adler = state->check = - UPDATE(state->check, put - out, out); - out = left; - if (( -#ifdef GUNZIP - state->flags ? hold : -#endif - REVERSE(hold)) != state->check) { - strm->msg = (char *)"incorrect data check"; - state->mode = BAD; - break; - } - INITBITS(); - Tracev((stderr, "inflate: check matches trailer\n")); - } -#ifdef GUNZIP - state->mode = LENGTH; - case LENGTH: - if (state->wrap && state->flags) { - NEEDBITS(32); - if (hold != (state->total & 0xffffffffUL)) { - strm->msg = (char *)"incorrect length check"; - state->mode = BAD; - break; - } - INITBITS(); - Tracev((stderr, "inflate: length matches trailer\n")); - } -#endif - state->mode = DONE; - case DONE: - ret = Z_STREAM_END; - goto inf_leave; - case BAD: - ret = Z_DATA_ERROR; - goto inf_leave; - case MEM: - return Z_MEM_ERROR; - case SYNC: - default: - return Z_STREAM_ERROR; - } - - /* - Return from inflate(), updating the total counts and the check value. - If there was no progress during the inflate() call, return a buffer - error. Call updatewindow() to create and/or update the window state. - Note: a memory error from inflate() is non-recoverable. - */ - inf_leave: - RESTORE(); - if (state->wsize || (state->mode < CHECK && out != strm->avail_out)) - if (updatewindow(strm, out)) { - state->mode = MEM; - return Z_MEM_ERROR; - } - in -= strm->avail_in; - out -= strm->avail_out; - strm->total_in += in; - strm->total_out += out; - state->total += out; - if (state->wrap && out) - strm->adler = state->check = - UPDATE(state->check, strm->next_out - out, out); - strm->data_type = state->bits + (state->last ? 64 : 0) + - (state->mode == TYPE ? 128 : 0); - if (((in == 0 && out == 0) || flush == Z_FINISH) && ret == Z_OK) - ret = Z_BUF_ERROR; - return ret; -} - -int ZEXPORT inflateEnd(strm) -z_streamp strm; -{ - struct inflate_state FAR *state; - if (strm == Z_NULL || strm->state == Z_NULL || strm->zfree == (free_func)0) - return Z_STREAM_ERROR; - state = (struct inflate_state FAR *)strm->state; - if (state->window != Z_NULL) ZFREE(strm, state->window); - ZFREE(strm, strm->state); - strm->state = Z_NULL; - Tracev((stderr, "inflate: end\n")); - return Z_OK; -} - -int ZEXPORT inflateSetDictionary(strm, dictionary, dictLength) -z_streamp strm; -const Bytef *dictionary; -uInt dictLength; -{ - struct inflate_state FAR *state; - unsigned long id; - - /* check state */ - if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; - state = (struct inflate_state FAR *)strm->state; - if (state->wrap != 0 && state->mode != DICT) - return Z_STREAM_ERROR; - - /* check for correct dictionary id */ - if (state->mode == DICT) { - id = adler32(0L, Z_NULL, 0); - id = adler32(id, dictionary, dictLength); - if (id != state->check) - return Z_DATA_ERROR; - } - - /* copy dictionary to window */ - if (updatewindow(strm, strm->avail_out)) { - state->mode = MEM; - return Z_MEM_ERROR; - } - if (dictLength > state->wsize) { - zmemcpy(state->window, dictionary + dictLength - state->wsize, - state->wsize); - state->whave = state->wsize; - } - else { - zmemcpy(state->window + state->wsize - dictLength, dictionary, - dictLength); - state->whave = dictLength; - } - state->havedict = 1; - Tracev((stderr, "inflate: dictionary set\n")); - return Z_OK; -} - -int ZEXPORT inflateGetHeader(strm, head) -z_streamp strm; -gz_headerp head; -{ - struct inflate_state FAR *state; - - /* check state */ - if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; - state = (struct inflate_state FAR *)strm->state; - if ((state->wrap & 2) == 0) return Z_STREAM_ERROR; - - /* save header structure */ - state->head = head; - head->done = 0; - return Z_OK; -} - -/* - Search buf[0..len-1] for the pattern: 0, 0, 0xff, 0xff. Return when found - or when out of input. When called, *have is the number of pattern bytes - found in order so far, in 0..3. On return *have is updated to the new - state. If on return *have equals four, then the pattern was found and the - return value is how many bytes were read including the last byte of the - pattern. If *have is less than four, then the pattern has not been found - yet and the return value is len. In the latter case, syncsearch() can be - called again with more data and the *have state. *have is initialized to - zero for the first call. - */ -local unsigned syncsearch(have, buf, len) -unsigned FAR *have; -unsigned char FAR *buf; -unsigned len; -{ - unsigned got; - unsigned next; - - got = *have; - next = 0; - while (next < len && got < 4) { - if ((int)(buf[next]) == (got < 2 ? 0 : 0xff)) - got++; - else if (buf[next]) - got = 0; - else - got = 4 - got; - next++; - } - *have = got; - return next; -} - -int ZEXPORT inflateSync(strm) -z_streamp strm; -{ - unsigned len; /* number of bytes to look at or looked at */ - unsigned long in, out; /* temporary to save total_in and total_out */ - unsigned char buf[4]; /* to restore bit buffer to byte string */ - struct inflate_state FAR *state; - - /* check parameters */ - if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; - state = (struct inflate_state FAR *)strm->state; - if (strm->avail_in == 0 && state->bits < 8) return Z_BUF_ERROR; - - /* if first time, start search in bit buffer */ - if (state->mode != SYNC) { - state->mode = SYNC; - state->hold <<= state->bits & 7; - state->bits -= state->bits & 7; - len = 0; - while (state->bits >= 8) { - buf[len++] = (unsigned char)(state->hold); - state->hold >>= 8; - state->bits -= 8; - } - state->have = 0; - syncsearch(&(state->have), buf, len); - } - - /* search available input */ - len = syncsearch(&(state->have), strm->next_in, strm->avail_in); - strm->avail_in -= len; - strm->next_in += len; - strm->total_in += len; - - /* return no joy or set up to restart inflate() on a new block */ - if (state->have != 4) return Z_DATA_ERROR; - in = strm->total_in; out = strm->total_out; - inflateReset(strm); - strm->total_in = in; strm->total_out = out; - state->mode = TYPE; - return Z_OK; -} - -/* - Returns true if inflate is currently at the end of a block generated by - Z_SYNC_FLUSH or Z_FULL_FLUSH. This function is used by one PPP - implementation to provide an additional safety check. PPP uses - Z_SYNC_FLUSH but removes the length bytes of the resulting empty stored - block. When decompressing, PPP checks that at the end of input packet, - inflate is waiting for these length bytes. - */ -int ZEXPORT inflateSyncPoint(strm) -z_streamp strm; -{ - struct inflate_state FAR *state; - - if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; - state = (struct inflate_state FAR *)strm->state; - return state->mode == STORED && state->bits == 0; -} - -int ZEXPORT inflateCopy(dest, source) -z_streamp dest; -z_streamp source; -{ - struct inflate_state FAR *state; - struct inflate_state FAR *copy; - unsigned char FAR *window; - unsigned wsize; - - /* check input */ - if (dest == Z_NULL || source == Z_NULL || source->state == Z_NULL || - source->zalloc == (alloc_func)0 || source->zfree == (free_func)0) - return Z_STREAM_ERROR; - state = (struct inflate_state FAR *)source->state; - - /* allocate space */ - copy = (struct inflate_state FAR *) - ZALLOC(source, 1, sizeof(struct inflate_state)); - if (copy == Z_NULL) return Z_MEM_ERROR; - window = Z_NULL; - if (state->window != Z_NULL) { - window = (unsigned char FAR *) - ZALLOC(source, 1U << state->wbits, sizeof(unsigned char)); - if (window == Z_NULL) { - ZFREE(source, copy); - return Z_MEM_ERROR; - } - } - - /* copy state */ - zmemcpy(dest, source, sizeof(z_stream)); - zmemcpy(copy, state, sizeof(struct inflate_state)); - if (state->lencode >= state->codes && - state->lencode <= state->codes + ENOUGH - 1) { - copy->lencode = copy->codes + (state->lencode - state->codes); - copy->distcode = copy->codes + (state->distcode - state->codes); - } - copy->next = copy->codes + (state->next - state->codes); - if (window != Z_NULL) { - wsize = 1U << state->wbits; - zmemcpy(window, state->window, wsize); - } - copy->window = window; - dest->state = (struct internal_state FAR *)copy; - return Z_OK; -} diff --git a/sourcepawn/third_party/zlib/inflate.h b/sourcepawn/third_party/zlib/inflate.h deleted file mode 100644 index fbbc8714..00000000 --- a/sourcepawn/third_party/zlib/inflate.h +++ /dev/null @@ -1,115 +0,0 @@ -/* inflate.h -- internal inflate state definition - * Copyright (C) 1995-2004 Mark Adler - * For conditions of distribution and use, see copyright notice in zlib.h - */ - -/* WARNING: this file should *not* be used by applications. It is - part of the implementation of the compression library and is - subject to change. Applications should only use zlib.h. - */ - -/* define NO_GZIP when compiling if you want to disable gzip header and - trailer decoding by inflate(). NO_GZIP would be used to avoid linking in - the crc code when it is not needed. For shared libraries, gzip decoding - should be left enabled. */ -#ifndef NO_GZIP -# define GUNZIP -#endif - -/* Possible inflate modes between inflate() calls */ -typedef enum { - HEAD, /* i: waiting for magic header */ - FLAGS, /* i: waiting for method and flags (gzip) */ - TIME, /* i: waiting for modification time (gzip) */ - OS, /* i: waiting for extra flags and operating system (gzip) */ - EXLEN, /* i: waiting for extra length (gzip) */ - EXTRA, /* i: waiting for extra bytes (gzip) */ - NAME, /* i: waiting for end of file name (gzip) */ - COMMENT, /* i: waiting for end of comment (gzip) */ - HCRC, /* i: waiting for header crc (gzip) */ - DICTID, /* i: waiting for dictionary check value */ - DICT, /* waiting for inflateSetDictionary() call */ - TYPE, /* i: waiting for type bits, including last-flag bit */ - TYPEDO, /* i: same, but skip check to exit inflate on new block */ - STORED, /* i: waiting for stored size (length and complement) */ - COPY, /* i/o: waiting for input or output to copy stored block */ - TABLE, /* i: waiting for dynamic block table lengths */ - LENLENS, /* i: waiting for code length code lengths */ - CODELENS, /* i: waiting for length/lit and distance code lengths */ - LEN, /* i: waiting for length/lit code */ - LENEXT, /* i: waiting for length extra bits */ - DIST, /* i: waiting for distance code */ - DISTEXT, /* i: waiting for distance extra bits */ - MATCH, /* o: waiting for output space to copy string */ - LIT, /* o: waiting for output space to write literal */ - CHECK, /* i: waiting for 32-bit check value */ - LENGTH, /* i: waiting for 32-bit length (gzip) */ - DONE, /* finished check, done -- remain here until reset */ - BAD, /* got a data error -- remain here until reset */ - MEM, /* got an inflate() memory error -- remain here until reset */ - SYNC /* looking for synchronization bytes to restart inflate() */ -} inflate_mode; - -/* - State transitions between above modes - - - (most modes can go to the BAD or MEM mode -- not shown for clarity) - - Process header: - HEAD -> (gzip) or (zlib) - (gzip) -> FLAGS -> TIME -> OS -> EXLEN -> EXTRA -> NAME - NAME -> COMMENT -> HCRC -> TYPE - (zlib) -> DICTID or TYPE - DICTID -> DICT -> TYPE - Read deflate blocks: - TYPE -> STORED or TABLE or LEN or CHECK - STORED -> COPY -> TYPE - TABLE -> LENLENS -> CODELENS -> LEN - Read deflate codes: - LEN -> LENEXT or LIT or TYPE - LENEXT -> DIST -> DISTEXT -> MATCH -> LEN - LIT -> LEN - Process trailer: - CHECK -> LENGTH -> DONE - */ - -/* state maintained between inflate() calls. Approximately 7K bytes. */ -struct inflate_state { - inflate_mode mode; /* current inflate mode */ - int last; /* true if processing last block */ - int wrap; /* bit 0 true for zlib, bit 1 true for gzip */ - int havedict; /* true if dictionary provided */ - int flags; /* gzip header method and flags (0 if zlib) */ - unsigned dmax; /* zlib header max distance (INFLATE_STRICT) */ - unsigned long check; /* protected copy of check value */ - unsigned long total; /* protected copy of output count */ - gz_headerp head; /* where to save gzip header information */ - /* sliding window */ - unsigned wbits; /* log base 2 of requested window size */ - unsigned wsize; /* window size or zero if not using window */ - unsigned whave; /* valid bytes in the window */ - unsigned write; /* window write index */ - unsigned char FAR *window; /* allocated sliding window, if needed */ - /* bit accumulator */ - unsigned long hold; /* input bit accumulator */ - unsigned bits; /* number of bits in "in" */ - /* for string and stored block copying */ - unsigned length; /* literal or length of data to copy */ - unsigned offset; /* distance back to copy string from */ - /* for table and code decoding */ - unsigned extra; /* extra bits needed */ - /* fixed and dynamic code tables */ - code const FAR *lencode; /* starting table for length/literal codes */ - code const FAR *distcode; /* starting table for distance codes */ - unsigned lenbits; /* index bits for lencode */ - unsigned distbits; /* index bits for distcode */ - /* dynamic table building */ - unsigned ncode; /* number of code length code lengths */ - unsigned nlen; /* number of length code lengths */ - unsigned ndist; /* number of distance code lengths */ - unsigned have; /* number of code lengths in lens[] */ - code FAR *next; /* next available space in codes[] */ - unsigned short lens[320]; /* temporary storage for code lengths */ - unsigned short work[288]; /* work area for code table building */ - code codes[ENOUGH]; /* space for code tables */ -}; diff --git a/sourcepawn/third_party/zlib/inftrees.c b/sourcepawn/third_party/zlib/inftrees.c deleted file mode 100644 index a1406443..00000000 --- a/sourcepawn/third_party/zlib/inftrees.c +++ /dev/null @@ -1,330 +0,0 @@ -/* inftrees.c -- generate Huffman trees for efficient decoding - * Copyright (C) 1995-2005 Mark Adler - * For conditions of distribution and use, see copyright notice in zlib.h - */ - -#include -#include "zutil.h" -#include "inftrees.h" - -#define MAXBITS 15 - -const char inflate_copyright[] = - " inflate 1.2.3 Copyright 1995-2005 Mark Adler "; -/* - If you use the zlib library in a product, an acknowledgment is welcome - in the documentation of your product. If for some reason you cannot - include such an acknowledgment, I would appreciate that you keep this - copyright string in the executable of your product. - */ - -/* - Build a set of tables to decode the provided canonical Huffman code. - The code lengths are lens[0..codes-1]. The result starts at *table, - whose indices are 0..2^bits-1. work is a writable array of at least - lens shorts, which is used as a work area. type is the type of code - to be generated, CODES, LENS, or DISTS. On return, zero is success, - -1 is an invalid code, and +1 means that ENOUGH isn't enough. table - on return points to the next available entry's address. bits is the - requested root table index bits, and on return it is the actual root - table index bits. It will differ if the request is greater than the - longest code or if it is less than the shortest code. - */ -int inflate_table(type, lens, codes, table, bits, work) -codetype type; -unsigned short FAR *lens; -unsigned codes; -code FAR * FAR *table; -unsigned FAR *bits; -unsigned short FAR *work; -{ - unsigned len; /* a code's length in bits */ - unsigned sym; /* index of code symbols */ - unsigned min, max; /* minimum and maximum code lengths */ - unsigned root; /* number of index bits for root table */ - unsigned curr; /* number of index bits for current table */ - unsigned drop; /* code bits to drop for sub-table */ - int left; /* number of prefix codes available */ - unsigned used; /* code entries in table used */ - unsigned huff; /* Huffman code */ - unsigned incr; /* for incrementing code, index */ - unsigned fill; /* index for replicating entries */ - unsigned low; /* low bits for current root entry */ - unsigned mask; /* mask for low root bits */ - code this; /* table entry for duplication */ - code FAR *next; /* next available space in table */ - const unsigned short FAR *base; /* base value table to use */ - const unsigned short FAR *extra; /* extra bits table to use */ - int end; /* use base and extra for symbol > end */ - unsigned short count[MAXBITS+1]; /* number of codes of each length */ - unsigned short offs[MAXBITS+1]; /* offsets in table for each length */ - static const unsigned short lbase[31] = { /* Length codes 257..285 base */ - 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, - 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0}; - static const unsigned short lext[31] = { /* Length codes 257..285 extra */ - 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18, - 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 201, 196}; - static const unsigned short dbase[32] = { /* Distance codes 0..29 base */ - 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, - 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, - 8193, 12289, 16385, 24577, 0, 0}; - static const unsigned short dext[32] = { /* Distance codes 0..29 extra */ - 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22, - 23, 23, 24, 24, 25, 25, 26, 26, 27, 27, - 28, 28, 29, 29, 64, 64}; - - /* - Process a set of code lengths to create a canonical Huffman code. The - code lengths are lens[0..codes-1]. Each length corresponds to the - symbols 0..codes-1. The Huffman code is generated by first sorting the - symbols by length from short to long, and retaining the symbol order - for codes with equal lengths. Then the code starts with all zero bits - for the first code of the shortest length, and the codes are integer - increments for the same length, and zeros are appended as the length - increases. For the deflate format, these bits are stored backwards - from their more natural integer increment ordering, and so when the - decoding tables are built in the large loop below, the integer codes - are incremented backwards. - - This routine assumes, but does not check, that all of the entries in - lens[] are in the range 0..MAXBITS. The caller must assure this. - 1..MAXBITS is interpreted as that code length. zero means that that - symbol does not occur in this code. - - The codes are sorted by computing a count of codes for each length, - creating from that a table of starting indices for each length in the - sorted table, and then entering the symbols in order in the sorted - table. The sorted table is work[], with that space being provided by - the caller. - - The length counts are used for other purposes as well, i.e. finding - the minimum and maximum length codes, determining if there are any - codes at all, checking for a valid set of lengths, and looking ahead - at length counts to determine sub-table sizes when building the - decoding tables. - */ - - /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */ - for (len = 0; len <= MAXBITS; len++) - count[len] = 0; - for (sym = 0; sym < codes; sym++) - count[lens[sym]]++; - - /* bound code lengths, force root to be within code lengths */ - root = *bits; - for (max = MAXBITS; max >= 1; max--) - if (count[max] != 0) break; - if (root > max) root = max; - if (max == 0) { /* no symbols to code at all */ - this.op = (unsigned char)64; /* invalid code marker */ - this.bits = (unsigned char)1; - this.val = (unsigned short)0; - *(*table)++ = this; /* make a table to force an error */ - *(*table)++ = this; - *bits = 1; - return 0; /* no symbols, but wait for decoding to report error */ - } - for (min = 1; min <= MAXBITS; min++) - if (count[min] != 0) break; - if (root < min) root = min; - - /* check for an over-subscribed or incomplete set of lengths */ - left = 1; - for (len = 1; len <= MAXBITS; len++) { - left <<= 1; - left -= count[len]; - if (left < 0) return -1; /* over-subscribed */ - } - if (left > 0 && (type == CODES || max != 1)) - return -1; /* incomplete set */ - - /* generate offsets into symbol table for each length for sorting */ - offs[1] = 0; - for (len = 1; len < MAXBITS; len++) - offs[len + 1] = offs[len] + count[len]; - - /* sort symbols by length, by symbol order within each length */ - for (sym = 0; sym < codes; sym++) - if (lens[sym] != 0) work[offs[lens[sym]]++] = (unsigned short)sym; - - /* - Create and fill in decoding tables. In this loop, the table being - filled is at next and has curr index bits. The code being used is huff - with length len. That code is converted to an index by dropping drop - bits off of the bottom. For codes where len is less than drop + curr, - those top drop + curr - len bits are incremented through all values to - fill the table with replicated entries. - - root is the number of index bits for the root table. When len exceeds - root, sub-tables are created pointed to by the root entry with an index - of the low root bits of huff. This is saved in low to check for when a - new sub-table should be started. drop is zero when the root table is - being filled, and drop is root when sub-tables are being filled. - - When a new sub-table is needed, it is necessary to look ahead in the - code lengths to determine what size sub-table is needed. The length - counts are used for this, and so count[] is decremented as codes are - entered in the tables. - - used keeps track of how many table entries have been allocated from the - provided *table space. It is checked when a LENS table is being made - against the space in *table, ENOUGH, minus the maximum space needed by - the worst case distance code, MAXD. This should never happen, but the - sufficiency of ENOUGH has not been proven exhaustively, hence the check. - This assumes that when type == LENS, bits == 9. - - sym increments through all symbols, and the loop terminates when - all codes of length max, i.e. all codes, have been processed. This - routine permits incomplete codes, so another loop after this one fills - in the rest of the decoding tables with invalid code markers. - */ - - /* set up for code type */ - switch (type) { - case CODES: - base = extra = work; /* dummy value--not used */ - end = 19; - break; - case LENS: - base = lbase; - base -= 257; - extra = lext; - extra -= 257; - end = 256; - break; - default: /* DISTS */ - base = dbase; - extra = dext; - end = -1; - } - - /* initialize state for loop */ - huff = 0; /* starting code */ - sym = 0; /* starting code symbol */ - len = min; /* starting code length */ - next = *table; /* current table to fill in */ - curr = root; /* current table index bits */ - drop = 0; /* current bits to drop from code for index */ - low = (unsigned)(-1); /* trigger new sub-table when len > root */ - used = 1U << root; /* use root table entries */ - mask = used - 1; /* mask for comparing low */ - - /* check available table space */ - if (type == LENS && used >= ENOUGH - MAXD) - return 1; - - /* process all codes and make table entries */ - for (;;) { - /* create table entry */ - this.bits = (unsigned char)(len - drop); - if ((int)(work[sym]) < end) { - this.op = (unsigned char)0; - this.val = work[sym]; - } - else if ((int)(work[sym]) > end) { - this.op = (unsigned char)(extra[work[sym]]); - this.val = base[work[sym]]; - } - else { - this.op = (unsigned char)(32 + 64); /* end of block */ - this.val = 0; - } - - /* replicate for those indices with low len bits equal to huff */ - incr = 1U << (len - drop); - fill = 1U << curr; - min = fill; /* save offset to next table */ - do { - fill -= incr; - next[(huff >> drop) + fill] = this; - } while (fill != 0); - - /* backwards increment the len-bit code huff */ - incr = 1U << (len - 1); - while (huff & incr) - incr >>= 1; - if (incr != 0) { - huff &= incr - 1; - huff += incr; - } - else - huff = 0; - - /* go to next symbol, update count, len */ - sym++; - if (--(count[len]) == 0) { - if (len == max) break; - len = lens[work[sym]]; - } - - /* create new sub-table if needed */ - if (len > root && (huff & mask) != low) { - /* if first time, transition to sub-tables */ - if (drop == 0) - drop = root; - - /* increment past last table */ - next += min; /* here min is 1 << curr */ - - /* determine length of next table */ - curr = len - drop; - left = (int)(1 << curr); - while (curr + drop < max) { - left -= count[curr + drop]; - if (left <= 0) break; - curr++; - left <<= 1; - } - - /* check for enough space */ - used += 1U << curr; - if (type == LENS && used >= ENOUGH - MAXD) - return 1; - - /* point entry in root table to sub-table */ - low = huff & mask; - (*table)[low].op = (unsigned char)curr; - (*table)[low].bits = (unsigned char)root; - (*table)[low].val = (unsigned short)(next - *table); - } - } - - /* - Fill in rest of table for incomplete codes. This loop is similar to the - loop above in incrementing huff for table indices. It is assumed that - len is equal to curr + drop, so there is no loop needed to increment - through high index bits. When the current sub-table is filled, the loop - drops back to the root table to fill in any remaining entries there. - */ - this.op = (unsigned char)64; /* invalid code marker */ - this.bits = (unsigned char)(len - drop); - this.val = (unsigned short)0; - while (huff != 0) { - /* when done with sub-table, drop back to root table */ - if (drop != 0 && (huff & mask) != low) { - drop = 0; - len = root; - next = *table; - this.bits = (unsigned char)len; - } - - /* put invalid code marker in table */ - next[huff >> drop] = this; - - /* backwards increment the len-bit code huff */ - incr = 1U << (len - 1); - while (huff & incr) - incr >>= 1; - if (incr != 0) { - huff &= incr - 1; - huff += incr; - } - else - huff = 0; - } - - /* set return parameters */ - *table += used; - *bits = root; - return 0; -} diff --git a/sourcepawn/third_party/zlib/inftrees.h b/sourcepawn/third_party/zlib/inftrees.h deleted file mode 100644 index dc0fd567..00000000 --- a/sourcepawn/third_party/zlib/inftrees.h +++ /dev/null @@ -1,55 +0,0 @@ -/* inftrees.h -- header to use inftrees.c - * Copyright (C) 1995-2005 Mark Adler - * For conditions of distribution and use, see copyright notice in zlib.h - */ - -/* WARNING: this file should *not* be used by applications. It is - part of the implementation of the compression library and is - subject to change. Applications should only use zlib.h. - */ - -/* Structure for decoding tables. Each entry provides either the - information needed to do the operation requested by the code that - indexed that table entry, or it provides a pointer to another - table that indexes more bits of the code. op indicates whether - the entry is a pointer to another table, a literal, a length or - distance, an end-of-block, or an invalid code. For a table - pointer, the low four bits of op is the number of index bits of - that table. For a length or distance, the low four bits of op - is the number of extra bits to get after the code. bits is - the number of bits in this code or part of the code to drop off - of the bit buffer. val is the actual byte to output in the case - of a literal, the base length or distance, or the offset from - the current table to the next table. Each entry is four bytes. */ -typedef struct { - unsigned char op; /* operation, extra bits, table bits */ - unsigned char bits; /* bits in this part of the code */ - unsigned short val; /* offset in table or code value */ -} code; - -/* op values as set by inflate_table(): - 00000000 - literal - 0000tttt - table link, tttt != 0 is the number of table index bits - 0001eeee - length or distance, eeee is the number of extra bits - 01100000 - end of block - 01000000 - invalid code - */ - -/* Maximum size of dynamic tree. The maximum found in a long but non- - exhaustive search was 1444 code structures (852 for length/literals - and 592 for distances, the latter actually the result of an - exhaustive search). The true maximum is not known, but the value - below is more than safe. */ -#define ENOUGH 2048 -#define MAXD 592 - -/* Type of code to build for inftable() */ -typedef enum { - CODES, - LENS, - DISTS -} codetype; - -extern int inflate_table OF((codetype type, unsigned short FAR *lens, - unsigned codes, code FAR * FAR *table, - unsigned FAR *bits, unsigned short FAR *work)); diff --git a/sourcepawn/third_party/zlib/trees.c b/sourcepawn/third_party/zlib/trees.c deleted file mode 100644 index 6ca02864..00000000 --- a/sourcepawn/third_party/zlib/trees.c +++ /dev/null @@ -1,1220 +0,0 @@ -/* trees.c -- output deflated data using Huffman coding - * Copyright (C) 1995-2005 Jean-loup Gailly - * For conditions of distribution and use, see copyright notice in zlib.h - */ - -/* - * ALGORITHM - * - * The "deflation" process uses several Huffman trees. The more - * common source values are represented by shorter bit sequences. - * - * Each code tree is stored in a compressed form which is itself - * a Huffman encoding of the lengths of all the code strings (in - * ascending order by source values). The actual code strings are - * reconstructed from the lengths in the inflate process, as described - * in the deflate specification. - * - * REFERENCES - * - * Deutsch, L.P.,"'Deflate' Compressed Data Format Specification". - * Available in ftp.uu.net:/pub/archiving/zip/doc/deflate-1.1.doc - * - * Storer, James A. - * Data Compression: Methods and Theory, pp. 49-50. - * Computer Science Press, 1988. ISBN 0-7167-8156-5. - * - * Sedgewick, R. - * Algorithms, p290. - * Addison-Wesley, 1983. ISBN 0-201-06672-6. - */ - -/* @(#) $Id$ */ - -/* #define GEN_TREES_H */ - -#include -#include "deflate.h" - -#ifdef DEBUG -# include -#endif - -/* =========================================================================== - * Constants - */ - -#define MAX_BL_BITS 7 -/* Bit length codes must not exceed MAX_BL_BITS bits */ - -#define END_BLOCK 256 -/* end of block literal code */ - -#define REP_3_6 16 -/* repeat previous bit length 3-6 times (2 bits of repeat count) */ - -#define REPZ_3_10 17 -/* repeat a zero length 3-10 times (3 bits of repeat count) */ - -#define REPZ_11_138 18 -/* repeat a zero length 11-138 times (7 bits of repeat count) */ - -local const int extra_lbits[LENGTH_CODES] /* extra bits for each length code */ - = {0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0}; - -local const int extra_dbits[D_CODES] /* extra bits for each distance code */ - = {0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13}; - -local const int extra_blbits[BL_CODES]/* extra bits for each bit length code */ - = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7}; - -local const uch bl_order[BL_CODES] - = {16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15}; -/* The lengths of the bit length codes are sent in order of decreasing - * probability, to avoid transmitting the lengths for unused bit length codes. - */ - -#define Buf_size (8 * 2*sizeof(char)) -/* Number of bits used within bi_buf. (bi_buf might be implemented on - * more than 16 bits on some systems.) - */ - -/* =========================================================================== - * Local data. These are initialized only once. - */ - -#define DIST_CODE_LEN 512 /* see definition of array dist_code below */ - -#if defined(GEN_TREES_H) || !defined(STDC) -/* non ANSI compilers may not accept trees.h */ - -local ct_data static_ltree[L_CODES+2]; -/* The static literal tree. Since the bit lengths are imposed, there is no - * need for the L_CODES extra codes used during heap construction. However - * The codes 286 and 287 are needed to build a canonical tree (see _tr_init - * below). - */ - -local ct_data static_dtree[D_CODES]; -/* The static distance tree. (Actually a trivial tree since all codes use - * 5 bits.) - */ - -uch _dist_code[DIST_CODE_LEN]; -/* Distance codes. The first 256 values correspond to the distances - * 3 .. 258, the last 256 values correspond to the top 8 bits of - * the 15 bit distances. - */ - -uch _length_code[MAX_MATCH-MIN_MATCH+1]; -/* length code for each normalized match length (0 == MIN_MATCH) */ - -local int base_length[LENGTH_CODES]; -/* First normalized length for each code (0 = MIN_MATCH) */ - -local int base_dist[D_CODES]; -/* First normalized distance for each code (0 = distance of 1) */ - -#else -# include "trees.h" -#endif /* GEN_TREES_H */ - -struct static_tree_desc_s { - const ct_data *static_tree; /* static tree or NULL */ - const intf *extra_bits; /* extra bits for each code or NULL */ - int extra_base; /* base index for extra_bits */ - int elems; /* max number of elements in the tree */ - int max_length; /* max bit length for the codes */ -}; - -local static_tree_desc static_l_desc = -{static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS}; - -local static_tree_desc static_d_desc = -{static_dtree, extra_dbits, 0, D_CODES, MAX_BITS}; - -local static_tree_desc static_bl_desc = -{(const ct_data *)0, extra_blbits, 0, BL_CODES, MAX_BL_BITS}; - -/* =========================================================================== - * Local (static) routines in this file. - */ - -local void tr_static_init OF((void)); -local void init_block OF((deflate_state *s)); -local void pqdownheap OF((deflate_state *s, ct_data *tree, int k)); -local void gen_bitlen OF((deflate_state *s, tree_desc *desc)); -local void gen_codes OF((ct_data *tree, int max_code, ushf *bl_count)); -local void build_tree OF((deflate_state *s, tree_desc *desc)); -local void scan_tree OF((deflate_state *s, ct_data *tree, int max_code)); -local void send_tree OF((deflate_state *s, ct_data *tree, int max_code)); -local int build_bl_tree OF((deflate_state *s)); -local void send_all_trees OF((deflate_state *s, int lcodes, int dcodes, - int blcodes)); -local void compress_block OF((deflate_state *s, ct_data *ltree, - ct_data *dtree)); -local void set_data_type OF((deflate_state *s)); -local unsigned bi_reverse OF((unsigned value, int length)); -local void bi_windup OF((deflate_state *s)); -local void bi_flush OF((deflate_state *s)); -local void copy_block OF((deflate_state *s, charf *buf, unsigned len, - int header)); - -#ifdef GEN_TREES_H -local void gen_trees_header OF((void)); -#endif - -#ifndef DEBUG -# define send_code(s, c, tree) send_bits(s, tree[c].Code, tree[c].Len) - /* Send a code of the given tree. c and tree must not have side effects */ - -#else /* DEBUG */ -# define send_code(s, c, tree) \ - { if (z_verbose>2) fprintf(stderr,"\ncd %3d ",(c)); \ - send_bits(s, tree[c].Code, tree[c].Len); } -#endif - -/* =========================================================================== - * Output a short LSB first on the stream. - * IN assertion: there is enough room in pendingBuf. - */ -#define put_short(s, w) { \ - put_byte(s, (uch)((w) & 0xff)); \ - put_byte(s, (uch)((ush)(w) >> 8)); \ -} - -/* =========================================================================== - * Send a value on a given number of bits. - * IN assertion: length <= 16 and value fits in length bits. - */ -#ifdef DEBUG -local void send_bits OF((deflate_state *s, int value, int length)); - -local void send_bits(s, value, length) - deflate_state *s; - int value; /* value to send */ - int length; /* number of bits */ -{ - Tracevv((stderr," l %2d v %4x ", length, value)); - Assert(length > 0 && length <= 15, "invalid length"); - s->bits_sent += (ulg)length; - - /* If not enough room in bi_buf, use (valid) bits from bi_buf and - * (16 - bi_valid) bits from value, leaving (width - (16-bi_valid)) - * unused bits in value. - */ - if (s->bi_valid > (int)Buf_size - length) { - s->bi_buf |= (value << s->bi_valid); - put_short(s, s->bi_buf); - s->bi_buf = (ush)value >> (Buf_size - s->bi_valid); - s->bi_valid += length - Buf_size; - } else { - s->bi_buf |= value << s->bi_valid; - s->bi_valid += length; - } -} -#else /* !DEBUG */ - -#define send_bits(s, value, length) \ -{ int len = length;\ - if (s->bi_valid > (int)Buf_size - len) {\ - int val = value;\ - s->bi_buf |= (val << s->bi_valid);\ - put_short(s, s->bi_buf);\ - s->bi_buf = (ush)val >> (Buf_size - s->bi_valid);\ - s->bi_valid += len - Buf_size;\ - } else {\ - s->bi_buf |= (value) << s->bi_valid;\ - s->bi_valid += len;\ - }\ -} -#endif /* DEBUG */ - - -/* the arguments must not have side effects */ - -/* =========================================================================== - * Initialize the various 'constant' tables. - */ -local void tr_static_init() -{ -#if defined(GEN_TREES_H) || !defined(STDC) - static int static_init_done = 0; - int n; /* iterates over tree elements */ - int bits; /* bit counter */ - int length; /* length value */ - int code; /* code value */ - int dist; /* distance index */ - ush bl_count[MAX_BITS+1]; - /* number of codes at each bit length for an optimal tree */ - - if (static_init_done) return; - - /* For some embedded targets, global variables are not initialized: */ - static_l_desc.static_tree = static_ltree; - static_l_desc.extra_bits = extra_lbits; - static_d_desc.static_tree = static_dtree; - static_d_desc.extra_bits = extra_dbits; - static_bl_desc.extra_bits = extra_blbits; - - /* Initialize the mapping length (0..255) -> length code (0..28) */ - length = 0; - for (code = 0; code < LENGTH_CODES-1; code++) { - base_length[code] = length; - for (n = 0; n < (1< dist code (0..29) */ - dist = 0; - for (code = 0 ; code < 16; code++) { - base_dist[code] = dist; - for (n = 0; n < (1<>= 7; /* from now on, all distances are divided by 128 */ - for ( ; code < D_CODES; code++) { - base_dist[code] = dist << 7; - for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) { - _dist_code[256 + dist++] = (uch)code; - } - } - Assert (dist == 256, "tr_static_init: 256+dist != 512"); - - /* Construct the codes of the static literal tree */ - for (bits = 0; bits <= MAX_BITS; bits++) bl_count[bits] = 0; - n = 0; - while (n <= 143) static_ltree[n++].Len = 8, bl_count[8]++; - while (n <= 255) static_ltree[n++].Len = 9, bl_count[9]++; - while (n <= 279) static_ltree[n++].Len = 7, bl_count[7]++; - while (n <= 287) static_ltree[n++].Len = 8, bl_count[8]++; - /* Codes 286 and 287 do not exist, but we must include them in the - * tree construction to get a canonical Huffman tree (longest code - * all ones) - */ - gen_codes((ct_data *)static_ltree, L_CODES+1, bl_count); - - /* The static distance tree is trivial: */ - for (n = 0; n < D_CODES; n++) { - static_dtree[n].Len = 5; - static_dtree[n].Code = bi_reverse((unsigned)n, 5); - } - static_init_done = 1; - -# ifdef GEN_TREES_H - gen_trees_header(); -# endif -#endif /* defined(GEN_TREES_H) || !defined(STDC) */ -} - -/* =========================================================================== - * Genererate the file trees.h describing the static trees. - */ -#ifdef GEN_TREES_H -# ifndef DEBUG -# include -# endif - -# define SEPARATOR(i, last, width) \ - ((i) == (last)? "\n};\n\n" : \ - ((i) % (width) == (width)-1 ? ",\n" : ", ")) - -void gen_trees_header() -{ - FILE *header = fopen("trees.h", "w"); - int i; - - Assert (header != NULL, "Can't open trees.h"); - fprintf(header, - "/* header created automatically with -DGEN_TREES_H */\n\n"); - - fprintf(header, "local const ct_data static_ltree[L_CODES+2] = {\n"); - for (i = 0; i < L_CODES+2; i++) { - fprintf(header, "{{%3u},{%3u}}%s", static_ltree[i].Code, - static_ltree[i].Len, SEPARATOR(i, L_CODES+1, 5)); - } - - fprintf(header, "local const ct_data static_dtree[D_CODES] = {\n"); - for (i = 0; i < D_CODES; i++) { - fprintf(header, "{{%2u},{%2u}}%s", static_dtree[i].Code, - static_dtree[i].Len, SEPARATOR(i, D_CODES-1, 5)); - } - - fprintf(header, "const uch _dist_code[DIST_CODE_LEN] = {\n"); - for (i = 0; i < DIST_CODE_LEN; i++) { - fprintf(header, "%2u%s", _dist_code[i], - SEPARATOR(i, DIST_CODE_LEN-1, 20)); - } - - fprintf(header, "const uch _length_code[MAX_MATCH-MIN_MATCH+1]= {\n"); - for (i = 0; i < MAX_MATCH-MIN_MATCH+1; i++) { - fprintf(header, "%2u%s", _length_code[i], - SEPARATOR(i, MAX_MATCH-MIN_MATCH, 20)); - } - - fprintf(header, "local const int base_length[LENGTH_CODES] = {\n"); - for (i = 0; i < LENGTH_CODES; i++) { - fprintf(header, "%1u%s", base_length[i], - SEPARATOR(i, LENGTH_CODES-1, 20)); - } - - fprintf(header, "local const int base_dist[D_CODES] = {\n"); - for (i = 0; i < D_CODES; i++) { - fprintf(header, "%5u%s", base_dist[i], - SEPARATOR(i, D_CODES-1, 10)); - } - - fclose(header); -} -#endif /* GEN_TREES_H */ - -/* =========================================================================== - * Initialize the tree data structures for a new zlib stream. - */ -void _tr_init(s) - deflate_state *s; -{ - tr_static_init(); - - s->l_desc.dyn_tree = s->dyn_ltree; - s->l_desc.stat_desc = &static_l_desc; - - s->d_desc.dyn_tree = s->dyn_dtree; - s->d_desc.stat_desc = &static_d_desc; - - s->bl_desc.dyn_tree = s->bl_tree; - s->bl_desc.stat_desc = &static_bl_desc; - - s->bi_buf = 0; - s->bi_valid = 0; - s->last_eob_len = 8; /* enough lookahead for inflate */ -#ifdef DEBUG - s->compressed_len = 0L; - s->bits_sent = 0L; -#endif - - /* Initialize the first block of the first file: */ - init_block(s); -} - -/* =========================================================================== - * Initialize a new block. - */ -local void init_block(s) - deflate_state *s; -{ - int n; /* iterates over tree elements */ - - /* Initialize the trees. */ - for (n = 0; n < L_CODES; n++) s->dyn_ltree[n].Freq = 0; - for (n = 0; n < D_CODES; n++) s->dyn_dtree[n].Freq = 0; - for (n = 0; n < BL_CODES; n++) s->bl_tree[n].Freq = 0; - - s->dyn_ltree[END_BLOCK].Freq = 1; - s->opt_len = s->static_len = 0L; - s->last_lit = s->matches = 0; -} - -#define SMALLEST 1 -/* Index within the heap array of least frequent node in the Huffman tree */ - - -/* =========================================================================== - * Remove the smallest element from the heap and recreate the heap with - * one less element. Updates heap and heap_len. - */ -#define pqremove(s, tree, top) \ -{\ - top = s->heap[SMALLEST]; \ - s->heap[SMALLEST] = s->heap[s->heap_len--]; \ - pqdownheap(s, tree, SMALLEST); \ -} - -/* =========================================================================== - * Compares to subtrees, using the tree depth as tie breaker when - * the subtrees have equal frequency. This minimizes the worst case length. - */ -#define smaller(tree, n, m, depth) \ - (tree[n].Freq < tree[m].Freq || \ - (tree[n].Freq == tree[m].Freq && depth[n] <= depth[m])) - -/* =========================================================================== - * Restore the heap property by moving down the tree starting at node k, - * exchanging a node with the smallest of its two sons if necessary, stopping - * when the heap property is re-established (each father smaller than its - * two sons). - */ -local void pqdownheap(s, tree, k) - deflate_state *s; - ct_data *tree; /* the tree to restore */ - int k; /* node to move down */ -{ - int v = s->heap[k]; - int j = k << 1; /* left son of k */ - while (j <= s->heap_len) { - /* Set j to the smallest of the two sons: */ - if (j < s->heap_len && - smaller(tree, s->heap[j+1], s->heap[j], s->depth)) { - j++; - } - /* Exit if v is smaller than both sons */ - if (smaller(tree, v, s->heap[j], s->depth)) break; - - /* Exchange v with the smallest son */ - s->heap[k] = s->heap[j]; k = j; - - /* And continue down the tree, setting j to the left son of k */ - j <<= 1; - } - s->heap[k] = v; -} - -/* =========================================================================== - * Compute the optimal bit lengths for a tree and update the total bit length - * for the current block. - * IN assertion: the fields freq and dad are set, heap[heap_max] and - * above are the tree nodes sorted by increasing frequency. - * OUT assertions: the field len is set to the optimal bit length, the - * array bl_count contains the frequencies for each bit length. - * The length opt_len is updated; static_len is also updated if stree is - * not null. - */ -local void gen_bitlen(s, desc) - deflate_state *s; - tree_desc *desc; /* the tree descriptor */ -{ - ct_data *tree = desc->dyn_tree; - int max_code = desc->max_code; - const ct_data *stree = desc->stat_desc->static_tree; - const intf *extra = desc->stat_desc->extra_bits; - int base = desc->stat_desc->extra_base; - int max_length = desc->stat_desc->max_length; - int h; /* heap index */ - int n, m; /* iterate over the tree elements */ - int bits; /* bit length */ - int xbits; /* extra bits */ - ush f; /* frequency */ - int overflow = 0; /* number of elements with bit length too large */ - - for (bits = 0; bits <= MAX_BITS; bits++) s->bl_count[bits] = 0; - - /* In a first pass, compute the optimal bit lengths (which may - * overflow in the case of the bit length tree). - */ - tree[s->heap[s->heap_max]].Len = 0; /* root of the heap */ - - for (h = s->heap_max+1; h < HEAP_SIZE; h++) { - n = s->heap[h]; - bits = tree[tree[n].Dad].Len + 1; - if (bits > max_length) bits = max_length, overflow++; - tree[n].Len = (ush)bits; - /* We overwrite tree[n].Dad which is no longer needed */ - - if (n > max_code) continue; /* not a leaf node */ - - s->bl_count[bits]++; - xbits = 0; - if (n >= base) xbits = extra[n-base]; - f = tree[n].Freq; - s->opt_len += (ulg)f * (bits + xbits); - if (stree) s->static_len += (ulg)f * (stree[n].Len + xbits); - } - if (overflow == 0) return; - - Trace((stderr,"\nbit length overflow\n")); - /* This happens for example on obj2 and pic of the Calgary corpus */ - - /* Find the first bit length which could increase: */ - do { - bits = max_length-1; - while (s->bl_count[bits] == 0) bits--; - s->bl_count[bits]--; /* move one leaf down the tree */ - s->bl_count[bits+1] += 2; /* move one overflow item as its brother */ - s->bl_count[max_length]--; - /* The brother of the overflow item also moves one step up, - * but this does not affect bl_count[max_length] - */ - overflow -= 2; - } while (overflow > 0); - - /* Now recompute all bit lengths, scanning in increasing frequency. - * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all - * lengths instead of fixing only the wrong ones. This idea is taken - * from 'ar' written by Haruhiko Okumura.) - */ - for (bits = max_length; bits != 0; bits--) { - n = s->bl_count[bits]; - while (n != 0) { - m = s->heap[--h]; - if (m > max_code) continue; - if ((unsigned) tree[m].Len != (unsigned) bits) { - Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits)); - s->opt_len += ((long)bits - (long)tree[m].Len) - *(long)tree[m].Freq; - tree[m].Len = (ush)bits; - } - n--; - } - } -} - -/* =========================================================================== - * Generate the codes for a given tree and bit counts (which need not be - * optimal). - * IN assertion: the array bl_count contains the bit length statistics for - * the given tree and the field len is set for all tree elements. - * OUT assertion: the field code is set for all tree elements of non - * zero code length. - */ -local void gen_codes (tree, max_code, bl_count) - ct_data *tree; /* the tree to decorate */ - int max_code; /* largest code with non zero frequency */ - ushf *bl_count; /* number of codes at each bit length */ -{ - ush next_code[MAX_BITS+1]; /* next code value for each bit length */ - ush code = 0; /* running code value */ - int bits; /* bit index */ - int n; /* code index */ - - /* The distribution counts are first used to generate the code values - * without bit reversal. - */ - for (bits = 1; bits <= MAX_BITS; bits++) { - next_code[bits] = code = (code + bl_count[bits-1]) << 1; - } - /* Check that the bit counts in bl_count are consistent. The last code - * must be all ones. - */ - Assert (code + bl_count[MAX_BITS]-1 == (1<dyn_tree; - const ct_data *stree = desc->stat_desc->static_tree; - int elems = desc->stat_desc->elems; - int n, m; /* iterate over heap elements */ - int max_code = -1; /* largest code with non zero frequency */ - int node; /* new node being created */ - - /* Construct the initial heap, with least frequent element in - * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1]. - * heap[0] is not used. - */ - s->heap_len = 0, s->heap_max = HEAP_SIZE; - - for (n = 0; n < elems; n++) { - if (tree[n].Freq != 0) { - s->heap[++(s->heap_len)] = max_code = n; - s->depth[n] = 0; - } else { - tree[n].Len = 0; - } - } - - /* The pkzip format requires that at least one distance code exists, - * and that at least one bit should be sent even if there is only one - * possible code. So to avoid special checks later on we force at least - * two codes of non zero frequency. - */ - while (s->heap_len < 2) { - node = s->heap[++(s->heap_len)] = (max_code < 2 ? ++max_code : 0); - tree[node].Freq = 1; - s->depth[node] = 0; - s->opt_len--; if (stree) s->static_len -= stree[node].Len; - /* node is 0 or 1 so it does not have extra bits */ - } - desc->max_code = max_code; - - /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree, - * establish sub-heaps of increasing lengths: - */ - for (n = s->heap_len/2; n >= 1; n--) pqdownheap(s, tree, n); - - /* Construct the Huffman tree by repeatedly combining the least two - * frequent nodes. - */ - node = elems; /* next internal node of the tree */ - do { - pqremove(s, tree, n); /* n = node of least frequency */ - m = s->heap[SMALLEST]; /* m = node of next least frequency */ - - s->heap[--(s->heap_max)] = n; /* keep the nodes sorted by frequency */ - s->heap[--(s->heap_max)] = m; - - /* Create a new node father of n and m */ - tree[node].Freq = tree[n].Freq + tree[m].Freq; - s->depth[node] = (uch)((s->depth[n] >= s->depth[m] ? - s->depth[n] : s->depth[m]) + 1); - tree[n].Dad = tree[m].Dad = (ush)node; -#ifdef DUMP_BL_TREE - if (tree == s->bl_tree) { - fprintf(stderr,"\nnode %d(%d), sons %d(%d) %d(%d)", - node, tree[node].Freq, n, tree[n].Freq, m, tree[m].Freq); - } -#endif - /* and insert the new node in the heap */ - s->heap[SMALLEST] = node++; - pqdownheap(s, tree, SMALLEST); - - } while (s->heap_len >= 2); - - s->heap[--(s->heap_max)] = s->heap[SMALLEST]; - - /* At this point, the fields freq and dad are set. We can now - * generate the bit lengths. - */ - gen_bitlen(s, (tree_desc *)desc); - - /* The field len is now set, we can generate the bit codes */ - gen_codes ((ct_data *)tree, max_code, s->bl_count); -} - -/* =========================================================================== - * Scan a literal or distance tree to determine the frequencies of the codes - * in the bit length tree. - */ -local void scan_tree (s, tree, max_code) - deflate_state *s; - ct_data *tree; /* the tree to be scanned */ - int max_code; /* and its largest code of non zero frequency */ -{ - int n; /* iterates over all tree elements */ - int prevlen = -1; /* last emitted length */ - int curlen; /* length of current code */ - int nextlen = tree[0].Len; /* length of next code */ - int count = 0; /* repeat count of the current code */ - int max_count = 7; /* max repeat count */ - int min_count = 4; /* min repeat count */ - - if (nextlen == 0) max_count = 138, min_count = 3; - tree[max_code+1].Len = (ush)0xffff; /* guard */ - - for (n = 0; n <= max_code; n++) { - curlen = nextlen; nextlen = tree[n+1].Len; - if (++count < max_count && curlen == nextlen) { - continue; - } else if (count < min_count) { - s->bl_tree[curlen].Freq += count; - } else if (curlen != 0) { - if (curlen != prevlen) s->bl_tree[curlen].Freq++; - s->bl_tree[REP_3_6].Freq++; - } else if (count <= 10) { - s->bl_tree[REPZ_3_10].Freq++; - } else { - s->bl_tree[REPZ_11_138].Freq++; - } - count = 0; prevlen = curlen; - if (nextlen == 0) { - max_count = 138, min_count = 3; - } else if (curlen == nextlen) { - max_count = 6, min_count = 3; - } else { - max_count = 7, min_count = 4; - } - } -} - -/* =========================================================================== - * Send a literal or distance tree in compressed form, using the codes in - * bl_tree. - */ -local void send_tree (s, tree, max_code) - deflate_state *s; - ct_data *tree; /* the tree to be scanned */ - int max_code; /* and its largest code of non zero frequency */ -{ - int n; /* iterates over all tree elements */ - int prevlen = -1; /* last emitted length */ - int curlen; /* length of current code */ - int nextlen = tree[0].Len; /* length of next code */ - int count = 0; /* repeat count of the current code */ - int max_count = 7; /* max repeat count */ - int min_count = 4; /* min repeat count */ - - /* tree[max_code+1].Len = -1; */ /* guard already set */ - if (nextlen == 0) max_count = 138, min_count = 3; - - for (n = 0; n <= max_code; n++) { - curlen = nextlen; nextlen = tree[n+1].Len; - if (++count < max_count && curlen == nextlen) { - continue; - } else if (count < min_count) { - do { send_code(s, curlen, s->bl_tree); } while (--count != 0); - - } else if (curlen != 0) { - if (curlen != prevlen) { - send_code(s, curlen, s->bl_tree); count--; - } - Assert(count >= 3 && count <= 6, " 3_6?"); - send_code(s, REP_3_6, s->bl_tree); send_bits(s, count-3, 2); - - } else if (count <= 10) { - send_code(s, REPZ_3_10, s->bl_tree); send_bits(s, count-3, 3); - - } else { - send_code(s, REPZ_11_138, s->bl_tree); send_bits(s, count-11, 7); - } - count = 0; prevlen = curlen; - if (nextlen == 0) { - max_count = 138, min_count = 3; - } else if (curlen == nextlen) { - max_count = 6, min_count = 3; - } else { - max_count = 7, min_count = 4; - } - } -} - -/* =========================================================================== - * Construct the Huffman tree for the bit lengths and return the index in - * bl_order of the last bit length code to send. - */ -local int build_bl_tree(s) - deflate_state *s; -{ - int max_blindex; /* index of last bit length code of non zero freq */ - - /* Determine the bit length frequencies for literal and distance trees */ - scan_tree(s, (ct_data *)s->dyn_ltree, s->l_desc.max_code); - scan_tree(s, (ct_data *)s->dyn_dtree, s->d_desc.max_code); - - /* Build the bit length tree: */ - build_tree(s, (tree_desc *)(&(s->bl_desc))); - /* opt_len now includes the length of the tree representations, except - * the lengths of the bit lengths codes and the 5+5+4 bits for the counts. - */ - - /* Determine the number of bit length codes to send. The pkzip format - * requires that at least 4 bit length codes be sent. (appnote.txt says - * 3 but the actual value used is 4.) - */ - for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) { - if (s->bl_tree[bl_order[max_blindex]].Len != 0) break; - } - /* Update opt_len to include the bit length tree and counts */ - s->opt_len += 3*(max_blindex+1) + 5+5+4; - Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld", - s->opt_len, s->static_len)); - - return max_blindex; -} - -/* =========================================================================== - * Send the header for a block using dynamic Huffman trees: the counts, the - * lengths of the bit length codes, the literal tree and the distance tree. - * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4. - */ -local void send_all_trees(s, lcodes, dcodes, blcodes) - deflate_state *s; - int lcodes, dcodes, blcodes; /* number of codes for each tree */ -{ - int rank; /* index in bl_order */ - - Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes"); - Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES, - "too many codes"); - Tracev((stderr, "\nbl counts: ")); - send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */ - send_bits(s, dcodes-1, 5); - send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */ - for (rank = 0; rank < blcodes; rank++) { - Tracev((stderr, "\nbl code %2d ", bl_order[rank])); - send_bits(s, s->bl_tree[bl_order[rank]].Len, 3); - } - Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent)); - - send_tree(s, (ct_data *)s->dyn_ltree, lcodes-1); /* literal tree */ - Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent)); - - send_tree(s, (ct_data *)s->dyn_dtree, dcodes-1); /* distance tree */ - Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent)); -} - -/* =========================================================================== - * Send a stored block - */ -void _tr_stored_block(s, buf, stored_len, eof) - deflate_state *s; - charf *buf; /* input block */ - ulg stored_len; /* length of input block */ - int eof; /* true if this is the last block for a file */ -{ - send_bits(s, (STORED_BLOCK<<1)+eof, 3); /* send block type */ -#ifdef DEBUG - s->compressed_len = (s->compressed_len + 3 + 7) & (ulg)~7L; - s->compressed_len += (stored_len + 4) << 3; -#endif - copy_block(s, buf, (unsigned)stored_len, 1); /* with header */ -} - -/* =========================================================================== - * Send one empty static block to give enough lookahead for inflate. - * This takes 10 bits, of which 7 may remain in the bit buffer. - * The current inflate code requires 9 bits of lookahead. If the - * last two codes for the previous block (real code plus EOB) were coded - * on 5 bits or less, inflate may have only 5+3 bits of lookahead to decode - * the last real code. In this case we send two empty static blocks instead - * of one. (There are no problems if the previous block is stored or fixed.) - * To simplify the code, we assume the worst case of last real code encoded - * on one bit only. - */ -void _tr_align(s) - deflate_state *s; -{ - send_bits(s, STATIC_TREES<<1, 3); - send_code(s, END_BLOCK, static_ltree); -#ifdef DEBUG - s->compressed_len += 10L; /* 3 for block type, 7 for EOB */ -#endif - bi_flush(s); - /* Of the 10 bits for the empty block, we have already sent - * (10 - bi_valid) bits. The lookahead for the last real code (before - * the EOB of the previous block) was thus at least one plus the length - * of the EOB plus what we have just sent of the empty static block. - */ - if (1 + s->last_eob_len + 10 - s->bi_valid < 9) { - send_bits(s, STATIC_TREES<<1, 3); - send_code(s, END_BLOCK, static_ltree); -#ifdef DEBUG - s->compressed_len += 10L; -#endif - bi_flush(s); - } - s->last_eob_len = 7; -} - -/* =========================================================================== - * Determine the best encoding for the current block: dynamic trees, static - * trees or store, and output the encoded block to the zip file. - */ -void _tr_flush_block(s, buf, stored_len, eof) - deflate_state *s; - charf *buf; /* input block, or NULL if too old */ - ulg stored_len; /* length of input block */ - int eof; /* true if this is the last block for a file */ -{ - ulg opt_lenb, static_lenb; /* opt_len and static_len in bytes */ - int max_blindex = 0; /* index of last bit length code of non zero freq */ - - /* Build the Huffman trees unless a stored block is forced */ - if (s->level > 0) { - - /* Check if the file is binary or text */ - if (stored_len > 0 && s->strm->data_type == Z_UNKNOWN) - set_data_type(s); - - /* Construct the literal and distance trees */ - build_tree(s, (tree_desc *)(&(s->l_desc))); - Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len, - s->static_len)); - - build_tree(s, (tree_desc *)(&(s->d_desc))); - Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len, - s->static_len)); - /* At this point, opt_len and static_len are the total bit lengths of - * the compressed block data, excluding the tree representations. - */ - - /* Build the bit length tree for the above two trees, and get the index - * in bl_order of the last bit length code to send. - */ - max_blindex = build_bl_tree(s); - - /* Determine the best encoding. Compute the block lengths in bytes. */ - opt_lenb = (s->opt_len+3+7)>>3; - static_lenb = (s->static_len+3+7)>>3; - - Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ", - opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len, - s->last_lit)); - - if (static_lenb <= opt_lenb) opt_lenb = static_lenb; - - } else { - Assert(buf != (char*)0, "lost buf"); - opt_lenb = static_lenb = stored_len + 5; /* force a stored block */ - } - -#ifdef FORCE_STORED - if (buf != (char*)0) { /* force stored block */ -#else - if (stored_len+4 <= opt_lenb && buf != (char*)0) { - /* 4: two words for the lengths */ -#endif - /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE. - * Otherwise we can't have processed more than WSIZE input bytes since - * the last block flush, because compression would have been - * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to - * transform a block into a stored block. - */ - _tr_stored_block(s, buf, stored_len, eof); - -#ifdef FORCE_STATIC - } else if (static_lenb >= 0) { /* force static trees */ -#else - } else if (s->strategy == Z_FIXED || static_lenb == opt_lenb) { -#endif - send_bits(s, (STATIC_TREES<<1)+eof, 3); - compress_block(s, (ct_data *)static_ltree, (ct_data *)static_dtree); -#ifdef DEBUG - s->compressed_len += 3 + s->static_len; -#endif - } else { - send_bits(s, (DYN_TREES<<1)+eof, 3); - send_all_trees(s, s->l_desc.max_code+1, s->d_desc.max_code+1, - max_blindex+1); - compress_block(s, (ct_data *)s->dyn_ltree, (ct_data *)s->dyn_dtree); -#ifdef DEBUG - s->compressed_len += 3 + s->opt_len; -#endif - } - Assert (s->compressed_len == s->bits_sent, "bad compressed size"); - /* The above check is made mod 2^32, for files larger than 512 MB - * and uLong implemented on 32 bits. - */ - init_block(s); - - if (eof) { - bi_windup(s); -#ifdef DEBUG - s->compressed_len += 7; /* align on byte boundary */ -#endif - } - Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3, - s->compressed_len-7*eof)); -} - -/* =========================================================================== - * Save the match info and tally the frequency counts. Return true if - * the current block must be flushed. - */ -int _tr_tally (s, dist, lc) - deflate_state *s; - unsigned dist; /* distance of matched string */ - unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */ -{ - s->d_buf[s->last_lit] = (ush)dist; - s->l_buf[s->last_lit++] = (uch)lc; - if (dist == 0) { - /* lc is the unmatched char */ - s->dyn_ltree[lc].Freq++; - } else { - s->matches++; - /* Here, lc is the match length - MIN_MATCH */ - dist--; /* dist = match distance - 1 */ - Assert((ush)dist < (ush)MAX_DIST(s) && - (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) && - (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match"); - - s->dyn_ltree[_length_code[lc]+LITERALS+1].Freq++; - s->dyn_dtree[d_code(dist)].Freq++; - } - -#ifdef TRUNCATE_BLOCK - /* Try to guess if it is profitable to stop the current block here */ - if ((s->last_lit & 0x1fff) == 0 && s->level > 2) { - /* Compute an upper bound for the compressed length */ - ulg out_length = (ulg)s->last_lit*8L; - ulg in_length = (ulg)((long)s->strstart - s->block_start); - int dcode; - for (dcode = 0; dcode < D_CODES; dcode++) { - out_length += (ulg)s->dyn_dtree[dcode].Freq * - (5L+extra_dbits[dcode]); - } - out_length >>= 3; - Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ", - s->last_lit, in_length, out_length, - 100L - out_length*100L/in_length)); - if (s->matches < s->last_lit/2 && out_length < in_length/2) return 1; - } -#endif - return (s->last_lit == s->lit_bufsize-1); - /* We avoid equality with lit_bufsize because of wraparound at 64K - * on 16 bit machines and because stored blocks are restricted to - * 64K-1 bytes. - */ -} - -/* =========================================================================== - * Send the block data compressed using the given Huffman trees - */ -local void compress_block(s, ltree, dtree) - deflate_state *s; - ct_data *ltree; /* literal tree */ - ct_data *dtree; /* distance tree */ -{ - unsigned dist; /* distance of matched string */ - int lc; /* match length or unmatched char (if dist == 0) */ - unsigned lx = 0; /* running index in l_buf */ - unsigned code; /* the code to send */ - int extra; /* number of extra bits to send */ - - if (s->last_lit != 0) do { - dist = s->d_buf[lx]; - lc = s->l_buf[lx++]; - if (dist == 0) { - send_code(s, lc, ltree); /* send a literal byte */ - Tracecv(isgraph(lc), (stderr," '%c' ", lc)); - } else { - /* Here, lc is the match length - MIN_MATCH */ - code = _length_code[lc]; - send_code(s, code+LITERALS+1, ltree); /* send the length code */ - extra = extra_lbits[code]; - if (extra != 0) { - lc -= base_length[code]; - send_bits(s, lc, extra); /* send the extra length bits */ - } - dist--; /* dist is now the match distance - 1 */ - code = d_code(dist); - Assert (code < D_CODES, "bad d_code"); - - send_code(s, code, dtree); /* send the distance code */ - extra = extra_dbits[code]; - if (extra != 0) { - dist -= base_dist[code]; - send_bits(s, dist, extra); /* send the extra distance bits */ - } - } /* literal or match pair ? */ - - /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */ - Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx, - "pendingBuf overflow"); - - } while (lx < s->last_lit); - - send_code(s, END_BLOCK, ltree); - s->last_eob_len = ltree[END_BLOCK].Len; -} - -/* =========================================================================== - * Set the data type to BINARY or TEXT, using a crude approximation: - * set it to Z_TEXT if all symbols are either printable characters (33 to 255) - * or white spaces (9 to 13, or 32); or set it to Z_BINARY otherwise. - * IN assertion: the fields Freq of dyn_ltree are set. - */ -local void set_data_type(s) - deflate_state *s; -{ - int n; - - for (n = 0; n < 9; n++) - if (s->dyn_ltree[n].Freq != 0) - break; - if (n == 9) - for (n = 14; n < 32; n++) - if (s->dyn_ltree[n].Freq != 0) - break; - s->strm->data_type = (n == 32) ? Z_TEXT : Z_BINARY; -} - -/* =========================================================================== - * Reverse the first len bits of a code, using straightforward code (a faster - * method would use a table) - * IN assertion: 1 <= len <= 15 - */ -local unsigned bi_reverse(code, len) - unsigned code; /* the value to invert */ - int len; /* its bit length */ -{ - register unsigned res = 0; - do { - res |= code & 1; - code >>= 1, res <<= 1; - } while (--len > 0); - return res >> 1; -} - -/* =========================================================================== - * Flush the bit buffer, keeping at most 7 bits in it. - */ -local void bi_flush(s) - deflate_state *s; -{ - if (s->bi_valid == 16) { - put_short(s, s->bi_buf); - s->bi_buf = 0; - s->bi_valid = 0; - } else if (s->bi_valid >= 8) { - put_byte(s, (Byte)s->bi_buf); - s->bi_buf >>= 8; - s->bi_valid -= 8; - } -} - -/* =========================================================================== - * Flush the bit buffer and align the output on a byte boundary - */ -local void bi_windup(s) - deflate_state *s; -{ - if (s->bi_valid > 8) { - put_short(s, s->bi_buf); - } else if (s->bi_valid > 0) { - put_byte(s, (Byte)s->bi_buf); - } - s->bi_buf = 0; - s->bi_valid = 0; -#ifdef DEBUG - s->bits_sent = (s->bits_sent+7) & ~7; -#endif -} - -/* =========================================================================== - * Copy a stored block, storing first the length and its - * one's complement if requested. - */ -local void copy_block(s, buf, len, header) - deflate_state *s; - charf *buf; /* the input data */ - unsigned len; /* its length */ - int header; /* true if block header must be written */ -{ - bi_windup(s); /* align on byte boundary */ - s->last_eob_len = 8; /* enough lookahead for inflate */ - - if (header) { - put_short(s, (ush)len); - put_short(s, (ush)~len); -#ifdef DEBUG - s->bits_sent += 2*16; -#endif - } -#ifdef DEBUG - s->bits_sent += (ulg)len<<3; -#endif - while (len--) { - put_byte(s, *buf++); - } -} diff --git a/sourcepawn/third_party/zlib/trees.h b/sourcepawn/third_party/zlib/trees.h deleted file mode 100644 index 1ca868b8..00000000 --- a/sourcepawn/third_party/zlib/trees.h +++ /dev/null @@ -1,128 +0,0 @@ -/* header created automatically with -DGEN_TREES_H */ - -local const ct_data static_ltree[L_CODES+2] = { -{{ 12},{ 8}}, {{140},{ 8}}, {{ 76},{ 8}}, {{204},{ 8}}, {{ 44},{ 8}}, -{{172},{ 8}}, {{108},{ 8}}, {{236},{ 8}}, {{ 28},{ 8}}, {{156},{ 8}}, -{{ 92},{ 8}}, {{220},{ 8}}, {{ 60},{ 8}}, {{188},{ 8}}, {{124},{ 8}}, -{{252},{ 8}}, {{ 2},{ 8}}, {{130},{ 8}}, {{ 66},{ 8}}, {{194},{ 8}}, -{{ 34},{ 8}}, {{162},{ 8}}, {{ 98},{ 8}}, {{226},{ 8}}, {{ 18},{ 8}}, -{{146},{ 8}}, {{ 82},{ 8}}, {{210},{ 8}}, {{ 50},{ 8}}, {{178},{ 8}}, -{{114},{ 8}}, {{242},{ 8}}, {{ 10},{ 8}}, {{138},{ 8}}, {{ 74},{ 8}}, -{{202},{ 8}}, {{ 42},{ 8}}, {{170},{ 8}}, {{106},{ 8}}, {{234},{ 8}}, -{{ 26},{ 8}}, {{154},{ 8}}, {{ 90},{ 8}}, {{218},{ 8}}, {{ 58},{ 8}}, -{{186},{ 8}}, {{122},{ 8}}, {{250},{ 8}}, {{ 6},{ 8}}, {{134},{ 8}}, -{{ 70},{ 8}}, {{198},{ 8}}, {{ 38},{ 8}}, {{166},{ 8}}, {{102},{ 8}}, -{{230},{ 8}}, {{ 22},{ 8}}, {{150},{ 8}}, {{ 86},{ 8}}, {{214},{ 8}}, -{{ 54},{ 8}}, {{182},{ 8}}, {{118},{ 8}}, {{246},{ 8}}, {{ 14},{ 8}}, -{{142},{ 8}}, {{ 78},{ 8}}, {{206},{ 8}}, {{ 46},{ 8}}, {{174},{ 8}}, -{{110},{ 8}}, {{238},{ 8}}, {{ 30},{ 8}}, {{158},{ 8}}, {{ 94},{ 8}}, -{{222},{ 8}}, {{ 62},{ 8}}, {{190},{ 8}}, {{126},{ 8}}, {{254},{ 8}}, -{{ 1},{ 8}}, {{129},{ 8}}, {{ 65},{ 8}}, {{193},{ 8}}, {{ 33},{ 8}}, -{{161},{ 8}}, {{ 97},{ 8}}, {{225},{ 8}}, {{ 17},{ 8}}, {{145},{ 8}}, -{{ 81},{ 8}}, {{209},{ 8}}, {{ 49},{ 8}}, {{177},{ 8}}, {{113},{ 8}}, -{{241},{ 8}}, {{ 9},{ 8}}, {{137},{ 8}}, {{ 73},{ 8}}, {{201},{ 8}}, -{{ 41},{ 8}}, {{169},{ 8}}, {{105},{ 8}}, {{233},{ 8}}, {{ 25},{ 8}}, -{{153},{ 8}}, {{ 89},{ 8}}, {{217},{ 8}}, {{ 57},{ 8}}, {{185},{ 8}}, -{{121},{ 8}}, {{249},{ 8}}, {{ 5},{ 8}}, {{133},{ 8}}, {{ 69},{ 8}}, -{{197},{ 8}}, {{ 37},{ 8}}, {{165},{ 8}}, {{101},{ 8}}, {{229},{ 8}}, -{{ 21},{ 8}}, {{149},{ 8}}, {{ 85},{ 8}}, {{213},{ 8}}, {{ 53},{ 8}}, -{{181},{ 8}}, {{117},{ 8}}, {{245},{ 8}}, {{ 13},{ 8}}, {{141},{ 8}}, -{{ 77},{ 8}}, {{205},{ 8}}, {{ 45},{ 8}}, {{173},{ 8}}, {{109},{ 8}}, -{{237},{ 8}}, {{ 29},{ 8}}, {{157},{ 8}}, {{ 93},{ 8}}, {{221},{ 8}}, -{{ 61},{ 8}}, {{189},{ 8}}, {{125},{ 8}}, {{253},{ 8}}, {{ 19},{ 9}}, -{{275},{ 9}}, {{147},{ 9}}, {{403},{ 9}}, {{ 83},{ 9}}, {{339},{ 9}}, -{{211},{ 9}}, {{467},{ 9}}, {{ 51},{ 9}}, {{307},{ 9}}, {{179},{ 9}}, -{{435},{ 9}}, {{115},{ 9}}, {{371},{ 9}}, {{243},{ 9}}, {{499},{ 9}}, -{{ 11},{ 9}}, {{267},{ 9}}, {{139},{ 9}}, {{395},{ 9}}, {{ 75},{ 9}}, -{{331},{ 9}}, {{203},{ 9}}, {{459},{ 9}}, {{ 43},{ 9}}, {{299},{ 9}}, -{{171},{ 9}}, {{427},{ 9}}, {{107},{ 9}}, {{363},{ 9}}, {{235},{ 9}}, -{{491},{ 9}}, {{ 27},{ 9}}, {{283},{ 9}}, {{155},{ 9}}, {{411},{ 9}}, -{{ 91},{ 9}}, {{347},{ 9}}, {{219},{ 9}}, {{475},{ 9}}, {{ 59},{ 9}}, -{{315},{ 9}}, {{187},{ 9}}, {{443},{ 9}}, {{123},{ 9}}, {{379},{ 9}}, -{{251},{ 9}}, {{507},{ 9}}, {{ 7},{ 9}}, {{263},{ 9}}, {{135},{ 9}}, -{{391},{ 9}}, {{ 71},{ 9}}, {{327},{ 9}}, {{199},{ 9}}, {{455},{ 9}}, -{{ 39},{ 9}}, {{295},{ 9}}, {{167},{ 9}}, {{423},{ 9}}, {{103},{ 9}}, -{{359},{ 9}}, {{231},{ 9}}, {{487},{ 9}}, {{ 23},{ 9}}, {{279},{ 9}}, -{{151},{ 9}}, {{407},{ 9}}, {{ 87},{ 9}}, {{343},{ 9}}, {{215},{ 9}}, -{{471},{ 9}}, {{ 55},{ 9}}, {{311},{ 9}}, {{183},{ 9}}, {{439},{ 9}}, -{{119},{ 9}}, {{375},{ 9}}, {{247},{ 9}}, {{503},{ 9}}, {{ 15},{ 9}}, -{{271},{ 9}}, {{143},{ 9}}, {{399},{ 9}}, {{ 79},{ 9}}, {{335},{ 9}}, -{{207},{ 9}}, {{463},{ 9}}, {{ 47},{ 9}}, {{303},{ 9}}, {{175},{ 9}}, -{{431},{ 9}}, {{111},{ 9}}, {{367},{ 9}}, {{239},{ 9}}, {{495},{ 9}}, -{{ 31},{ 9}}, {{287},{ 9}}, {{159},{ 9}}, {{415},{ 9}}, {{ 95},{ 9}}, -{{351},{ 9}}, {{223},{ 9}}, {{479},{ 9}}, {{ 63},{ 9}}, {{319},{ 9}}, -{{191},{ 9}}, {{447},{ 9}}, {{127},{ 9}}, {{383},{ 9}}, {{255},{ 9}}, -{{511},{ 9}}, {{ 0},{ 7}}, {{ 64},{ 7}}, {{ 32},{ 7}}, {{ 96},{ 7}}, -{{ 16},{ 7}}, {{ 80},{ 7}}, {{ 48},{ 7}}, {{112},{ 7}}, {{ 8},{ 7}}, -{{ 72},{ 7}}, {{ 40},{ 7}}, {{104},{ 7}}, {{ 24},{ 7}}, {{ 88},{ 7}}, -{{ 56},{ 7}}, {{120},{ 7}}, {{ 4},{ 7}}, {{ 68},{ 7}}, {{ 36},{ 7}}, -{{100},{ 7}}, {{ 20},{ 7}}, {{ 84},{ 7}}, {{ 52},{ 7}}, {{116},{ 7}}, -{{ 3},{ 8}}, {{131},{ 8}}, {{ 67},{ 8}}, {{195},{ 8}}, {{ 35},{ 8}}, -{{163},{ 8}}, {{ 99},{ 8}}, {{227},{ 8}} -}; - -local const ct_data static_dtree[D_CODES] = { -{{ 0},{ 5}}, {{16},{ 5}}, {{ 8},{ 5}}, {{24},{ 5}}, {{ 4},{ 5}}, -{{20},{ 5}}, {{12},{ 5}}, {{28},{ 5}}, {{ 2},{ 5}}, {{18},{ 5}}, -{{10},{ 5}}, {{26},{ 5}}, {{ 6},{ 5}}, {{22},{ 5}}, {{14},{ 5}}, -{{30},{ 5}}, {{ 1},{ 5}}, {{17},{ 5}}, {{ 9},{ 5}}, {{25},{ 5}}, -{{ 5},{ 5}}, {{21},{ 5}}, {{13},{ 5}}, {{29},{ 5}}, {{ 3},{ 5}}, -{{19},{ 5}}, {{11},{ 5}}, {{27},{ 5}}, {{ 7},{ 5}}, {{23},{ 5}} -}; - -const uch _dist_code[DIST_CODE_LEN] = { - 0, 1, 2, 3, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, - 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10, -10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, -11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, -12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13, -13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, -13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, -14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, -14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, -14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15, -15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, -15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, -15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 16, 17, -18, 18, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 22, -23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, -24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, -26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, -26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, -27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, -27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, -28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, -28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, -28, 28, 28, 28, 28, 28, 28, 28, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, -29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, -29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, -29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29 -}; - -const uch _length_code[MAX_MATCH-MIN_MATCH+1]= { - 0, 1, 2, 3, 4, 5, 6, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 12, 12, -13, 13, 13, 13, 14, 14, 14, 14, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16, -17, 17, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19, -19, 19, 19, 19, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, -21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 22, 22, 22, 22, -22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 23, -23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, -24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, -25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, -25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26, -26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, -26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, -27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28 -}; - -local const int base_length[LENGTH_CODES] = { -0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 32, 40, 48, 56, -64, 80, 96, 112, 128, 160, 192, 224, 0 -}; - -local const int base_dist[D_CODES] = { - 0, 1, 2, 3, 4, 6, 8, 12, 16, 24, - 32, 48, 64, 96, 128, 192, 256, 384, 512, 768, - 1024, 1536, 2048, 3072, 4096, 6144, 8192, 12288, 16384, 24576 -}; - diff --git a/sourcepawn/third_party/zlib/uncompr.c b/sourcepawn/third_party/zlib/uncompr.c deleted file mode 100644 index ad6db0a6..00000000 --- a/sourcepawn/third_party/zlib/uncompr.c +++ /dev/null @@ -1,61 +0,0 @@ -/* uncompr.c -- decompress a memory buffer - * Copyright (C) 1995-2003 Jean-loup Gailly. - * For conditions of distribution and use, see copyright notice in zlib.h - */ - -/* @(#) $Id$ */ - -#define ZLIB_INTERNAL -#include "zlib.h" - -/* =========================================================================== - Decompresses the source buffer into the destination buffer. sourceLen is - the byte length of the source buffer. Upon entry, destLen is the total - size of the destination buffer, which must be large enough to hold the - entire uncompressed data. (The size of the uncompressed data must have - been saved previously by the compressor and transmitted to the decompressor - by some mechanism outside the scope of this compression library.) - Upon exit, destLen is the actual size of the compressed buffer. - This function can be used to decompress a whole file at once if the - input file is mmap'ed. - - uncompress returns Z_OK if success, Z_MEM_ERROR if there was not - enough memory, Z_BUF_ERROR if there was not enough room in the output - buffer, or Z_DATA_ERROR if the input data was corrupted. -*/ -int ZEXPORT uncompress (dest, destLen, source, sourceLen) - Bytef *dest; - uLongf *destLen; - const Bytef *source; - uLong sourceLen; -{ - z_stream stream; - int err; - - stream.next_in = (Bytef*)source; - stream.avail_in = (uInt)sourceLen; - /* Check for source > 64K on 16-bit machine: */ - if ((uLong)stream.avail_in != sourceLen) return Z_BUF_ERROR; - - stream.next_out = dest; - stream.avail_out = (uInt)*destLen; - if ((uLong)stream.avail_out != *destLen) return Z_BUF_ERROR; - - stream.zalloc = (alloc_func)0; - stream.zfree = (free_func)0; - - err = inflateInit(&stream); - if (err != Z_OK) return err; - - err = inflate(&stream, Z_FINISH); - if (err != Z_STREAM_END) { - inflateEnd(&stream); - if (err == Z_NEED_DICT || (err == Z_BUF_ERROR && stream.avail_in == 0)) - return Z_DATA_ERROR; - return err; - } - *destLen = stream.total_out; - - err = inflateEnd(&stream); - return err; -} diff --git a/sourcepawn/third_party/zlib/zconf.h b/sourcepawn/third_party/zlib/zconf.h deleted file mode 100644 index 59b5e7a6..00000000 --- a/sourcepawn/third_party/zlib/zconf.h +++ /dev/null @@ -1,281 +0,0 @@ -/* zconf.h -- configuration of the zlib compression library - * Copyright (C) 1995-2005 Jean-loup Gailly. - * For conditions of distribution and use, see copyright notice in zlib.h - */ - -/* @(#) $Id$ */ - -#ifndef ZCONF_H -#define ZCONF_H - -#if defined(__MSDOS__) && !defined(MSDOS) -# define MSDOS -#endif -#if (defined(OS_2) || defined(__OS2__)) && !defined(OS2) -# define OS2 -#endif -#if defined(_WINDOWS) && !defined(WINDOWS) -# define WINDOWS -#endif -#if defined(_WIN32) || defined(_WIN32_WCE) || defined(__WIN32__) -# ifndef WIN32 -# define WIN32 -# endif -#endif -#if (defined(MSDOS) || defined(OS2) || defined(WINDOWS)) && !defined(WIN32) -# if !defined(__GNUC__) && !defined(__FLAT__) && !defined(__386__) -# ifndef SYS16BIT -# define SYS16BIT -# endif -# endif -#endif - -/* - * Compile with -DMAXSEG_64K if the alloc function cannot allocate more - * than 64k bytes at a time (needed on systems with 16-bit int). - */ -#ifdef SYS16BIT -# define MAXSEG_64K -#endif -#ifdef MSDOS -# define UNALIGNED_OK -#endif - -#ifdef __STDC_VERSION__ -# ifndef STDC -# define STDC -# endif -# if __STDC_VERSION__ >= 199901L -# ifndef STDC99 -# define STDC99 -# endif -# endif -#endif -#if !defined(STDC) && (defined(__STDC__) || defined(__cplusplus)) -# define STDC -#endif -#if !defined(STDC) && (defined(__GNUC__) || defined(__BORLANDC__)) -# define STDC -#endif -#if !defined(STDC) && (defined(MSDOS) || defined(WINDOWS) || defined(WIN32)) -# define STDC -#endif -#if !defined(STDC) && (defined(OS2) || defined(__HOS_AIX__)) -# define STDC -#endif - -#if defined(__OS400__) && !defined(STDC) /* iSeries (formerly AS/400). */ -# define STDC -#endif - -#ifndef STDC -# ifndef const /* cannot use !defined(STDC) && !defined(const) on Mac */ -# define const /* note: need a more gentle solution here */ -# endif -#endif - -/* Some Mac compilers merge all .h files incorrectly: */ -#if defined(__MWERKS__)||defined(applec)||defined(THINK_C)||defined(__SC__) -# define NO_DUMMY_DECL -#endif - -/* Maximum value for memLevel in deflateInit2 */ -#ifndef MAX_MEM_LEVEL -# ifdef MAXSEG_64K -# define MAX_MEM_LEVEL 8 -# else -# define MAX_MEM_LEVEL 9 -# endif -#endif - -/* Maximum value for windowBits in deflateInit2 and inflateInit2. - * WARNING: reducing MAX_WBITS makes minigzip unable to extract .gz files - * created by gzip. (Files created by minigzip can still be extracted by - * gzip.) - */ -#ifndef MAX_WBITS -# define MAX_WBITS 15 /* 32K LZ77 window */ -#endif - -/* The memory requirements for deflate are (in bytes): - (1 << (windowBits+2)) + (1 << (memLevel+9)) - that is: 128K for windowBits=15 + 128K for memLevel = 8 (default values) - plus a few kilobytes for small objects. For example, if you want to reduce - the default memory requirements from 256K to 128K, compile with - make CFLAGS="-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7" - Of course this will generally degrade compression (there's no free lunch). - - The memory requirements for inflate are (in bytes) 1 << windowBits - that is, 32K for windowBits=15 (default value) plus a few kilobytes - for small objects. -*/ - - /* Type declarations */ - -#ifndef OF /* function prototypes */ -# ifdef STDC -# define OF(args) args -# else -# define OF(args) () -# endif -#endif - -/* The following definitions for FAR are needed only for MSDOS mixed - * model programming (small or medium model with some far allocations). - * This was tested only with MSC; for other MSDOS compilers you may have - * to define NO_MEMCPY in zutil.h. If you don't need the mixed model, - * just define FAR to be empty. - */ -#ifdef SYS16BIT -# if defined(M_I86SM) || defined(M_I86MM) - /* MSC small or medium model */ -# define SMALL_MEDIUM -# ifdef _MSC_VER -# define FAR _far -# else -# define FAR far -# endif -# endif -# if (defined(__SMALL__) || defined(__MEDIUM__)) - /* Turbo C small or medium model */ -# define SMALL_MEDIUM -# ifdef __BORLANDC__ -# define FAR _far -# else -# define FAR far -# endif -# endif -#endif - -#if defined(WINDOWS) || defined(WIN32) - /* If building or using zlib as a DLL, define ZLIB_DLL. - * This is not mandatory, but it offers a little performance increase. - */ -# ifdef ZLIB_DLL -# if defined(WIN32) && (!defined(__BORLANDC__) || (__BORLANDC__ >= 0x500)) -# ifdef ZLIB_INTERNAL -# define ZEXTERN extern __declspec(dllexport) -# else -# define ZEXTERN extern __declspec(dllimport) -# endif -# endif -# endif /* ZLIB_DLL */ - /* If building or using zlib with the WINAPI/WINAPIV calling convention, - * define ZLIB_WINAPI. - * Caution: the standard ZLIB1.DLL is NOT compiled using ZLIB_WINAPI. - */ -# ifdef ZLIB_WINAPI -# ifdef FAR -# undef FAR -# endif -# include - /* No need for _export, use ZLIB.DEF instead. */ - /* For complete Windows compatibility, use WINAPI, not __stdcall. */ -# define ZEXPORT WINAPI -# ifdef WIN32 -# define ZEXPORTVA WINAPIV -# else -# define ZEXPORTVA FAR CDECL -# endif -# endif -#endif - -#if defined (__BEOS__) -# ifdef ZLIB_DLL -# ifdef ZLIB_INTERNAL -# define ZEXPORT __declspec(dllexport) -# define ZEXPORTVA __declspec(dllexport) -# else -# define ZEXPORT __declspec(dllimport) -# define ZEXPORTVA __declspec(dllimport) -# endif -# endif -#endif - -#ifndef ZEXTERN -# define ZEXTERN extern -#endif -#ifndef ZEXPORT -# define ZEXPORT -#endif -#ifndef ZEXPORTVA -# define ZEXPORTVA -#endif - -#ifndef FAR -# define FAR -#endif - -#if !defined(__MACTYPES__) -typedef unsigned char Byte; /* 8 bits */ -#endif -typedef unsigned int uInt; /* 16 bits or more */ -typedef unsigned long uLong; /* 32 bits or more */ - -#ifdef SMALL_MEDIUM - /* Borland C/C++ and some old MSC versions ignore FAR inside typedef */ -# define Bytef Byte FAR -#else - typedef Byte FAR Bytef; -#endif -typedef char FAR charf; -typedef int FAR intf; -typedef uInt FAR uIntf; -typedef uLong FAR uLongf; - -#ifdef STDC - typedef void const *voidpc; - typedef void FAR *voidpf; - typedef void *voidp; -#else - typedef Byte const *voidpc; - typedef Byte FAR *voidpf; - typedef Byte *voidp; -#endif - -#if 0 /* HAVE_UNISTD_H -- this line is updated by ./configure */ -# include /* for off_t */ -# include /* for SEEK_* and off_t */ -# ifdef VMS -# include /* for off_t */ -# endif -# define z_off_t off_t -#endif -#ifndef SEEK_SET -# define SEEK_SET 0 /* Seek from beginning of file. */ -# define SEEK_CUR 1 /* Seek from current position. */ -# define SEEK_END 2 /* Set file pointer to EOF plus "offset" */ -#endif -#ifndef z_off_t -# define z_off_t long -#endif - -#if defined(__OS400__) -# define NO_vsnprintf -#endif - -#if defined(__MVS__) -# define NO_vsnprintf -# ifdef FAR -# undef FAR -# endif -#endif - -/* MVS linker does not support external names larger than 8 bytes */ -#if defined(__MVS__) -# pragma map(deflateInit_,"DEIN") -# pragma map(deflateInit2_,"DEIN2") -# pragma map(deflateEnd,"DEEND") -# pragma map(deflateBound,"DEBND") -# pragma map(inflateInit_,"ININ") -# pragma map(inflateInit2_,"ININ2") -# pragma map(inflateEnd,"INEND") -# pragma map(inflateSync,"INSY") -# pragma map(inflateSetDictionary,"INSEDI") -# pragma map(compressBound,"CMBND") -# pragma map(inflate_table,"INTABL") -# pragma map(inflate_fast,"INFA") -# pragma map(inflate_copyright,"INCOPY") -#endif - -#endif /* ZCONF_H */ diff --git a/sourcepawn/third_party/zlib/zlib.h b/sourcepawn/third_party/zlib/zlib.h deleted file mode 100644 index 62d0e467..00000000 --- a/sourcepawn/third_party/zlib/zlib.h +++ /dev/null @@ -1,1357 +0,0 @@ -/* zlib.h -- interface of the 'zlib' general purpose compression library - version 1.2.3, July 18th, 2005 - - Copyright (C) 1995-2005 Jean-loup Gailly and Mark Adler - - This software is provided 'as-is', without any express or implied - warranty. In no event will the authors be held liable for any damages - arising from the use of this software. - - Permission is granted to anyone to use this software for any purpose, - including commercial applications, and to alter it and redistribute it - freely, subject to the following restrictions: - - 1. The origin of this software must not be misrepresented; you must not - claim that you wrote the original software. If you use this software - in a product, an acknowledgment in the product documentation would be - appreciated but is not required. - 2. Altered source versions must be plainly marked as such, and must not be - misrepresented as being the original software. - 3. This notice may not be removed or altered from any source distribution. - - Jean-loup Gailly Mark Adler - jloup@gzip.org madler@alumni.caltech.edu - - - The data format used by the zlib library is described by RFCs (Request for - Comments) 1950 to 1952 in the files http://www.ietf.org/rfc/rfc1950.txt - (zlib format), rfc1951.txt (deflate format) and rfc1952.txt (gzip format). -*/ - -#ifndef ZLIB_H -#define ZLIB_H - -#include "zconf.h" - -#ifdef __cplusplus -extern "C" { -#endif - -#define ZLIB_VERSION "1.2.3" -#define ZLIB_VERNUM 0x1230 - -/* - The 'zlib' compression library provides in-memory compression and - decompression functions, including integrity checks of the uncompressed - data. This version of the library supports only one compression method - (deflation) but other algorithms will be added later and will have the same - stream interface. - - Compression can be done in a single step if the buffers are large - enough (for example if an input file is mmap'ed), or can be done by - repeated calls of the compression function. In the latter case, the - application must provide more input and/or consume the output - (providing more output space) before each call. - - The compressed data format used by default by the in-memory functions is - the zlib format, which is a zlib wrapper documented in RFC 1950, wrapped - around a deflate stream, which is itself documented in RFC 1951. - - The library also supports reading and writing files in gzip (.gz) format - with an interface similar to that of stdio using the functions that start - with "gz". The gzip format is different from the zlib format. gzip is a - gzip wrapper, documented in RFC 1952, wrapped around a deflate stream. - - This library can optionally read and write gzip streams in memory as well. - - The zlib format was designed to be compact and fast for use in memory - and on communications channels. The gzip format was designed for single- - file compression on file systems, has a larger header than zlib to maintain - directory information, and uses a different, slower check method than zlib. - - The library does not install any signal handler. The decoder checks - the consistency of the compressed data, so the library should never - crash even in case of corrupted input. -*/ - -typedef voidpf (*alloc_func) OF((voidpf opaque, uInt items, uInt size)); -typedef void (*free_func) OF((voidpf opaque, voidpf address)); - -struct internal_state; - -typedef struct z_stream_s { - Bytef *next_in; /* next input byte */ - uInt avail_in; /* number of bytes available at next_in */ - uLong total_in; /* total nb of input bytes read so far */ - - Bytef *next_out; /* next output byte should be put there */ - uInt avail_out; /* remaining free space at next_out */ - uLong total_out; /* total nb of bytes output so far */ - - char *msg; /* last error message, NULL if no error */ - struct internal_state FAR *state; /* not visible by applications */ - - alloc_func zalloc; /* used to allocate the internal state */ - free_func zfree; /* used to free the internal state */ - voidpf opaque; /* private data object passed to zalloc and zfree */ - - int data_type; /* best guess about the data type: binary or text */ - uLong adler; /* adler32 value of the uncompressed data */ - uLong reserved; /* reserved for future use */ -} z_stream; - -typedef z_stream FAR *z_streamp; - -/* - gzip header information passed to and from zlib routines. See RFC 1952 - for more details on the meanings of these fields. -*/ -typedef struct gz_header_s { - int text; /* true if compressed data believed to be text */ - uLong time; /* modification time */ - int xflags; /* extra flags (not used when writing a gzip file) */ - int os; /* operating system */ - Bytef *extra; /* pointer to extra field or Z_NULL if none */ - uInt extra_len; /* extra field length (valid if extra != Z_NULL) */ - uInt extra_max; /* space at extra (only when reading header) */ - Bytef *name; /* pointer to zero-terminated file name or Z_NULL */ - uInt name_max; /* space at name (only when reading header) */ - Bytef *comment; /* pointer to zero-terminated comment or Z_NULL */ - uInt comm_max; /* space at comment (only when reading header) */ - int hcrc; /* true if there was or will be a header crc */ - int done; /* true when done reading gzip header (not used - when writing a gzip file) */ -} gz_header; - -typedef gz_header FAR *gz_headerp; - -/* - The application must update next_in and avail_in when avail_in has - dropped to zero. It must update next_out and avail_out when avail_out - has dropped to zero. The application must initialize zalloc, zfree and - opaque before calling the init function. All other fields are set by the - compression library and must not be updated by the application. - - The opaque value provided by the application will be passed as the first - parameter for calls of zalloc and zfree. This can be useful for custom - memory management. The compression library attaches no meaning to the - opaque value. - - zalloc must return Z_NULL if there is not enough memory for the object. - If zlib is used in a multi-threaded application, zalloc and zfree must be - thread safe. - - On 16-bit systems, the functions zalloc and zfree must be able to allocate - exactly 65536 bytes, but will not be required to allocate more than this - if the symbol MAXSEG_64K is defined (see zconf.h). WARNING: On MSDOS, - pointers returned by zalloc for objects of exactly 65536 bytes *must* - have their offset normalized to zero. The default allocation function - provided by this library ensures this (see zutil.c). To reduce memory - requirements and avoid any allocation of 64K objects, at the expense of - compression ratio, compile the library with -DMAX_WBITS=14 (see zconf.h). - - The fields total_in and total_out can be used for statistics or - progress reports. After compression, total_in holds the total size of - the uncompressed data and may be saved for use in the decompressor - (particularly if the decompressor wants to decompress everything in - a single step). -*/ - - /* constants */ - -#define Z_NO_FLUSH 0 -#define Z_PARTIAL_FLUSH 1 /* will be removed, use Z_SYNC_FLUSH instead */ -#define Z_SYNC_FLUSH 2 -#define Z_FULL_FLUSH 3 -#define Z_FINISH 4 -#define Z_BLOCK 5 -/* Allowed flush values; see deflate() and inflate() below for details */ - -#define Z_OK 0 -#define Z_STREAM_END 1 -#define Z_NEED_DICT 2 -#define Z_ERRNO (-1) -#define Z_STREAM_ERROR (-2) -#define Z_DATA_ERROR (-3) -#define Z_MEM_ERROR (-4) -#define Z_BUF_ERROR (-5) -#define Z_VERSION_ERROR (-6) -/* Return codes for the compression/decompression functions. Negative - * values are errors, positive values are used for special but normal events. - */ - -#define Z_NO_COMPRESSION 0 -#define Z_BEST_SPEED 1 -#define Z_BEST_COMPRESSION 9 -#define Z_DEFAULT_COMPRESSION (-1) -/* compression levels */ - -#define Z_FILTERED 1 -#define Z_HUFFMAN_ONLY 2 -#define Z_RLE 3 -#define Z_FIXED 4 -#define Z_DEFAULT_STRATEGY 0 -/* compression strategy; see deflateInit2() below for details */ - -#define Z_BINARY 0 -#define Z_TEXT 1 -#define Z_ASCII Z_TEXT /* for compatibility with 1.2.2 and earlier */ -#define Z_UNKNOWN 2 -/* Possible values of the data_type field (though see inflate()) */ - -#define Z_DEFLATED 8 -/* The deflate compression method (the only one supported in this version) */ - -#define Z_NULL 0 /* for initializing zalloc, zfree, opaque */ - -#define zlib_version zlibVersion() -/* for compatibility with versions < 1.0.2 */ - - /* basic functions */ - -ZEXTERN const char * ZEXPORT zlibVersion OF((void)); -/* The application can compare zlibVersion and ZLIB_VERSION for consistency. - If the first character differs, the library code actually used is - not compatible with the zlib.h header file used by the application. - This check is automatically made by deflateInit and inflateInit. - */ - -/* -ZEXTERN int ZEXPORT deflateInit OF((z_streamp strm, int level)); - - Initializes the internal stream state for compression. The fields - zalloc, zfree and opaque must be initialized before by the caller. - If zalloc and zfree are set to Z_NULL, deflateInit updates them to - use default allocation functions. - - The compression level must be Z_DEFAULT_COMPRESSION, or between 0 and 9: - 1 gives best speed, 9 gives best compression, 0 gives no compression at - all (the input data is simply copied a block at a time). - Z_DEFAULT_COMPRESSION requests a default compromise between speed and - compression (currently equivalent to level 6). - - deflateInit returns Z_OK if success, Z_MEM_ERROR if there was not - enough memory, Z_STREAM_ERROR if level is not a valid compression level, - Z_VERSION_ERROR if the zlib library version (zlib_version) is incompatible - with the version assumed by the caller (ZLIB_VERSION). - msg is set to null if there is no error message. deflateInit does not - perform any compression: this will be done by deflate(). -*/ - - -ZEXTERN int ZEXPORT deflate OF((z_streamp strm, int flush)); -/* - deflate compresses as much data as possible, and stops when the input - buffer becomes empty or the output buffer becomes full. It may introduce some - output latency (reading input without producing any output) except when - forced to flush. - - The detailed semantics are as follows. deflate performs one or both of the - following actions: - - - Compress more input starting at next_in and update next_in and avail_in - accordingly. If not all input can be processed (because there is not - enough room in the output buffer), next_in and avail_in are updated and - processing will resume at this point for the next call of deflate(). - - - Provide more output starting at next_out and update next_out and avail_out - accordingly. This action is forced if the parameter flush is non zero. - Forcing flush frequently degrades the compression ratio, so this parameter - should be set only when necessary (in interactive applications). - Some output may be provided even if flush is not set. - - Before the call of deflate(), the application should ensure that at least - one of the actions is possible, by providing more input and/or consuming - more output, and updating avail_in or avail_out accordingly; avail_out - should never be zero before the call. The application can consume the - compressed output when it wants, for example when the output buffer is full - (avail_out == 0), or after each call of deflate(). If deflate returns Z_OK - and with zero avail_out, it must be called again after making room in the - output buffer because there might be more output pending. - - Normally the parameter flush is set to Z_NO_FLUSH, which allows deflate to - decide how much data to accumualte before producing output, in order to - maximize compression. - - If the parameter flush is set to Z_SYNC_FLUSH, all pending output is - flushed to the output buffer and the output is aligned on a byte boundary, so - that the decompressor can get all input data available so far. (In particular - avail_in is zero after the call if enough output space has been provided - before the call.) Flushing may degrade compression for some compression - algorithms and so it should be used only when necessary. - - If flush is set to Z_FULL_FLUSH, all output is flushed as with - Z_SYNC_FLUSH, and the compression state is reset so that decompression can - restart from this point if previous compressed data has been damaged or if - random access is desired. Using Z_FULL_FLUSH too often can seriously degrade - compression. - - If deflate returns with avail_out == 0, this function must be called again - with the same value of the flush parameter and more output space (updated - avail_out), until the flush is complete (deflate returns with non-zero - avail_out). In the case of a Z_FULL_FLUSH or Z_SYNC_FLUSH, make sure that - avail_out is greater than six to avoid repeated flush markers due to - avail_out == 0 on return. - - If the parameter flush is set to Z_FINISH, pending input is processed, - pending output is flushed and deflate returns with Z_STREAM_END if there - was enough output space; if deflate returns with Z_OK, this function must be - called again with Z_FINISH and more output space (updated avail_out) but no - more input data, until it returns with Z_STREAM_END or an error. After - deflate has returned Z_STREAM_END, the only possible operations on the - stream are deflateReset or deflateEnd. - - Z_FINISH can be used immediately after deflateInit if all the compression - is to be done in a single step. In this case, avail_out must be at least - the value returned by deflateBound (see below). If deflate does not return - Z_STREAM_END, then it must be called again as described above. - - deflate() sets strm->adler to the adler32 checksum of all input read - so far (that is, total_in bytes). - - deflate() may update strm->data_type if it can make a good guess about - the input data type (Z_BINARY or Z_TEXT). In doubt, the data is considered - binary. This field is only for information purposes and does not affect - the compression algorithm in any manner. - - deflate() returns Z_OK if some progress has been made (more input - processed or more output produced), Z_STREAM_END if all input has been - consumed and all output has been produced (only when flush is set to - Z_FINISH), Z_STREAM_ERROR if the stream state was inconsistent (for example - if next_in or next_out was NULL), Z_BUF_ERROR if no progress is possible - (for example avail_in or avail_out was zero). Note that Z_BUF_ERROR is not - fatal, and deflate() can be called again with more input and more output - space to continue compressing. -*/ - - -ZEXTERN int ZEXPORT deflateEnd OF((z_streamp strm)); -/* - All dynamically allocated data structures for this stream are freed. - This function discards any unprocessed input and does not flush any - pending output. - - deflateEnd returns Z_OK if success, Z_STREAM_ERROR if the - stream state was inconsistent, Z_DATA_ERROR if the stream was freed - prematurely (some input or output was discarded). In the error case, - msg may be set but then points to a static string (which must not be - deallocated). -*/ - - -/* -ZEXTERN int ZEXPORT inflateInit OF((z_streamp strm)); - - Initializes the internal stream state for decompression. The fields - next_in, avail_in, zalloc, zfree and opaque must be initialized before by - the caller. If next_in is not Z_NULL and avail_in is large enough (the exact - value depends on the compression method), inflateInit determines the - compression method from the zlib header and allocates all data structures - accordingly; otherwise the allocation will be deferred to the first call of - inflate. If zalloc and zfree are set to Z_NULL, inflateInit updates them to - use default allocation functions. - - inflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough - memory, Z_VERSION_ERROR if the zlib library version is incompatible with the - version assumed by the caller. msg is set to null if there is no error - message. inflateInit does not perform any decompression apart from reading - the zlib header if present: this will be done by inflate(). (So next_in and - avail_in may be modified, but next_out and avail_out are unchanged.) -*/ - - -ZEXTERN int ZEXPORT inflate OF((z_streamp strm, int flush)); -/* - inflate decompresses as much data as possible, and stops when the input - buffer becomes empty or the output buffer becomes full. It may introduce - some output latency (reading input without producing any output) except when - forced to flush. - - The detailed semantics are as follows. inflate performs one or both of the - following actions: - - - Decompress more input starting at next_in and update next_in and avail_in - accordingly. If not all input can be processed (because there is not - enough room in the output buffer), next_in is updated and processing - will resume at this point for the next call of inflate(). - - - Provide more output starting at next_out and update next_out and avail_out - accordingly. inflate() provides as much output as possible, until there - is no more input data or no more space in the output buffer (see below - about the flush parameter). - - Before the call of inflate(), the application should ensure that at least - one of the actions is possible, by providing more input and/or consuming - more output, and updating the next_* and avail_* values accordingly. - The application can consume the uncompressed output when it wants, for - example when the output buffer is full (avail_out == 0), or after each - call of inflate(). If inflate returns Z_OK and with zero avail_out, it - must be called again after making room in the output buffer because there - might be more output pending. - - The flush parameter of inflate() can be Z_NO_FLUSH, Z_SYNC_FLUSH, - Z_FINISH, or Z_BLOCK. Z_SYNC_FLUSH requests that inflate() flush as much - output as possible to the output buffer. Z_BLOCK requests that inflate() stop - if and when it gets to the next deflate block boundary. When decoding the - zlib or gzip format, this will cause inflate() to return immediately after - the header and before the first block. When doing a raw inflate, inflate() - will go ahead and process the first block, and will return when it gets to - the end of that block, or when it runs out of data. - - The Z_BLOCK option assists in appending to or combining deflate streams. - Also to assist in this, on return inflate() will set strm->data_type to the - number of unused bits in the last byte taken from strm->next_in, plus 64 - if inflate() is currently decoding the last block in the deflate stream, - plus 128 if inflate() returned immediately after decoding an end-of-block - code or decoding the complete header up to just before the first byte of the - deflate stream. The end-of-block will not be indicated until all of the - uncompressed data from that block has been written to strm->next_out. The - number of unused bits may in general be greater than seven, except when - bit 7 of data_type is set, in which case the number of unused bits will be - less than eight. - - inflate() should normally be called until it returns Z_STREAM_END or an - error. However if all decompression is to be performed in a single step - (a single call of inflate), the parameter flush should be set to - Z_FINISH. In this case all pending input is processed and all pending - output is flushed; avail_out must be large enough to hold all the - uncompressed data. (The size of the uncompressed data may have been saved - by the compressor for this purpose.) The next operation on this stream must - be inflateEnd to deallocate the decompression state. The use of Z_FINISH - is never required, but can be used to inform inflate that a faster approach - may be used for the single inflate() call. - - In this implementation, inflate() always flushes as much output as - possible to the output buffer, and always uses the faster approach on the - first call. So the only effect of the flush parameter in this implementation - is on the return value of inflate(), as noted below, or when it returns early - because Z_BLOCK is used. - - If a preset dictionary is needed after this call (see inflateSetDictionary - below), inflate sets strm->adler to the adler32 checksum of the dictionary - chosen by the compressor and returns Z_NEED_DICT; otherwise it sets - strm->adler to the adler32 checksum of all output produced so far (that is, - total_out bytes) and returns Z_OK, Z_STREAM_END or an error code as described - below. At the end of the stream, inflate() checks that its computed adler32 - checksum is equal to that saved by the compressor and returns Z_STREAM_END - only if the checksum is correct. - - inflate() will decompress and check either zlib-wrapped or gzip-wrapped - deflate data. The header type is detected automatically. Any information - contained in the gzip header is not retained, so applications that need that - information should instead use raw inflate, see inflateInit2() below, or - inflateBack() and perform their own processing of the gzip header and - trailer. - - inflate() returns Z_OK if some progress has been made (more input processed - or more output produced), Z_STREAM_END if the end of the compressed data has - been reached and all uncompressed output has been produced, Z_NEED_DICT if a - preset dictionary is needed at this point, Z_DATA_ERROR if the input data was - corrupted (input stream not conforming to the zlib format or incorrect check - value), Z_STREAM_ERROR if the stream structure was inconsistent (for example - if next_in or next_out was NULL), Z_MEM_ERROR if there was not enough memory, - Z_BUF_ERROR if no progress is possible or if there was not enough room in the - output buffer when Z_FINISH is used. Note that Z_BUF_ERROR is not fatal, and - inflate() can be called again with more input and more output space to - continue decompressing. If Z_DATA_ERROR is returned, the application may then - call inflateSync() to look for a good compression block if a partial recovery - of the data is desired. -*/ - - -ZEXTERN int ZEXPORT inflateEnd OF((z_streamp strm)); -/* - All dynamically allocated data structures for this stream are freed. - This function discards any unprocessed input and does not flush any - pending output. - - inflateEnd returns Z_OK if success, Z_STREAM_ERROR if the stream state - was inconsistent. In the error case, msg may be set but then points to a - static string (which must not be deallocated). -*/ - - /* Advanced functions */ - -/* - The following functions are needed only in some special applications. -*/ - -/* -ZEXTERN int ZEXPORT deflateInit2 OF((z_streamp strm, - int level, - int method, - int windowBits, - int memLevel, - int strategy)); - - This is another version of deflateInit with more compression options. The - fields next_in, zalloc, zfree and opaque must be initialized before by - the caller. - - The method parameter is the compression method. It must be Z_DEFLATED in - this version of the library. - - The windowBits parameter is the base two logarithm of the window size - (the size of the history buffer). It should be in the range 8..15 for this - version of the library. Larger values of this parameter result in better - compression at the expense of memory usage. The default value is 15 if - deflateInit is used instead. - - windowBits can also be -8..-15 for raw deflate. In this case, -windowBits - determines the window size. deflate() will then generate raw deflate data - with no zlib header or trailer, and will not compute an adler32 check value. - - windowBits can also be greater than 15 for optional gzip encoding. Add - 16 to windowBits to write a simple gzip header and trailer around the - compressed data instead of a zlib wrapper. The gzip header will have no - file name, no extra data, no comment, no modification time (set to zero), - no header crc, and the operating system will be set to 255 (unknown). If a - gzip stream is being written, strm->adler is a crc32 instead of an adler32. - - The memLevel parameter specifies how much memory should be allocated - for the internal compression state. memLevel=1 uses minimum memory but - is slow and reduces compression ratio; memLevel=9 uses maximum memory - for optimal speed. The default value is 8. See zconf.h for total memory - usage as a function of windowBits and memLevel. - - The strategy parameter is used to tune the compression algorithm. Use the - value Z_DEFAULT_STRATEGY for normal data, Z_FILTERED for data produced by a - filter (or predictor), Z_HUFFMAN_ONLY to force Huffman encoding only (no - string match), or Z_RLE to limit match distances to one (run-length - encoding). Filtered data consists mostly of small values with a somewhat - random distribution. In this case, the compression algorithm is tuned to - compress them better. The effect of Z_FILTERED is to force more Huffman - coding and less string matching; it is somewhat intermediate between - Z_DEFAULT and Z_HUFFMAN_ONLY. Z_RLE is designed to be almost as fast as - Z_HUFFMAN_ONLY, but give better compression for PNG image data. The strategy - parameter only affects the compression ratio but not the correctness of the - compressed output even if it is not set appropriately. Z_FIXED prevents the - use of dynamic Huffman codes, allowing for a simpler decoder for special - applications. - - deflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough - memory, Z_STREAM_ERROR if a parameter is invalid (such as an invalid - method). msg is set to null if there is no error message. deflateInit2 does - not perform any compression: this will be done by deflate(). -*/ - -ZEXTERN int ZEXPORT deflateSetDictionary OF((z_streamp strm, - const Bytef *dictionary, - uInt dictLength)); -/* - Initializes the compression dictionary from the given byte sequence - without producing any compressed output. This function must be called - immediately after deflateInit, deflateInit2 or deflateReset, before any - call of deflate. The compressor and decompressor must use exactly the same - dictionary (see inflateSetDictionary). - - The dictionary should consist of strings (byte sequences) that are likely - to be encountered later in the data to be compressed, with the most commonly - used strings preferably put towards the end of the dictionary. Using a - dictionary is most useful when the data to be compressed is short and can be - predicted with good accuracy; the data can then be compressed better than - with the default empty dictionary. - - Depending on the size of the compression data structures selected by - deflateInit or deflateInit2, a part of the dictionary may in effect be - discarded, for example if the dictionary is larger than the window size in - deflate or deflate2. Thus the strings most likely to be useful should be - put at the end of the dictionary, not at the front. In addition, the - current implementation of deflate will use at most the window size minus - 262 bytes of the provided dictionary. - - Upon return of this function, strm->adler is set to the adler32 value - of the dictionary; the decompressor may later use this value to determine - which dictionary has been used by the compressor. (The adler32 value - applies to the whole dictionary even if only a subset of the dictionary is - actually used by the compressor.) If a raw deflate was requested, then the - adler32 value is not computed and strm->adler is not set. - - deflateSetDictionary returns Z_OK if success, or Z_STREAM_ERROR if a - parameter is invalid (such as NULL dictionary) or the stream state is - inconsistent (for example if deflate has already been called for this stream - or if the compression method is bsort). deflateSetDictionary does not - perform any compression: this will be done by deflate(). -*/ - -ZEXTERN int ZEXPORT deflateCopy OF((z_streamp dest, - z_streamp source)); -/* - Sets the destination stream as a complete copy of the source stream. - - This function can be useful when several compression strategies will be - tried, for example when there are several ways of pre-processing the input - data with a filter. The streams that will be discarded should then be freed - by calling deflateEnd. Note that deflateCopy duplicates the internal - compression state which can be quite large, so this strategy is slow and - can consume lots of memory. - - deflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not - enough memory, Z_STREAM_ERROR if the source stream state was inconsistent - (such as zalloc being NULL). msg is left unchanged in both source and - destination. -*/ - -ZEXTERN int ZEXPORT deflateReset OF((z_streamp strm)); -/* - This function is equivalent to deflateEnd followed by deflateInit, - but does not free and reallocate all the internal compression state. - The stream will keep the same compression level and any other attributes - that may have been set by deflateInit2. - - deflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source - stream state was inconsistent (such as zalloc or state being NULL). -*/ - -ZEXTERN int ZEXPORT deflateParams OF((z_streamp strm, - int level, - int strategy)); -/* - Dynamically update the compression level and compression strategy. The - interpretation of level and strategy is as in deflateInit2. This can be - used to switch between compression and straight copy of the input data, or - to switch to a different kind of input data requiring a different - strategy. If the compression level is changed, the input available so far - is compressed with the old level (and may be flushed); the new level will - take effect only at the next call of deflate(). - - Before the call of deflateParams, the stream state must be set as for - a call of deflate(), since the currently available input may have to - be compressed and flushed. In particular, strm->avail_out must be non-zero. - - deflateParams returns Z_OK if success, Z_STREAM_ERROR if the source - stream state was inconsistent or if a parameter was invalid, Z_BUF_ERROR - if strm->avail_out was zero. -*/ - -ZEXTERN int ZEXPORT deflateTune OF((z_streamp strm, - int good_length, - int max_lazy, - int nice_length, - int max_chain)); -/* - Fine tune deflate's internal compression parameters. This should only be - used by someone who understands the algorithm used by zlib's deflate for - searching for the best matching string, and even then only by the most - fanatic optimizer trying to squeeze out the last compressed bit for their - specific input data. Read the deflate.c source code for the meaning of the - max_lazy, good_length, nice_length, and max_chain parameters. - - deflateTune() can be called after deflateInit() or deflateInit2(), and - returns Z_OK on success, or Z_STREAM_ERROR for an invalid deflate stream. - */ - -ZEXTERN uLong ZEXPORT deflateBound OF((z_streamp strm, - uLong sourceLen)); -/* - deflateBound() returns an upper bound on the compressed size after - deflation of sourceLen bytes. It must be called after deflateInit() - or deflateInit2(). This would be used to allocate an output buffer - for deflation in a single pass, and so would be called before deflate(). -*/ - -ZEXTERN int ZEXPORT deflatePrime OF((z_streamp strm, - int bits, - int value)); -/* - deflatePrime() inserts bits in the deflate output stream. The intent - is that this function is used to start off the deflate output with the - bits leftover from a previous deflate stream when appending to it. As such, - this function can only be used for raw deflate, and must be used before the - first deflate() call after a deflateInit2() or deflateReset(). bits must be - less than or equal to 16, and that many of the least significant bits of - value will be inserted in the output. - - deflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source - stream state was inconsistent. -*/ - -ZEXTERN int ZEXPORT deflateSetHeader OF((z_streamp strm, - gz_headerp head)); -/* - deflateSetHeader() provides gzip header information for when a gzip - stream is requested by deflateInit2(). deflateSetHeader() may be called - after deflateInit2() or deflateReset() and before the first call of - deflate(). The text, time, os, extra field, name, and comment information - in the provided gz_header structure are written to the gzip header (xflag is - ignored -- the extra flags are set according to the compression level). The - caller must assure that, if not Z_NULL, name and comment are terminated with - a zero byte, and that if extra is not Z_NULL, that extra_len bytes are - available there. If hcrc is true, a gzip header crc is included. Note that - the current versions of the command-line version of gzip (up through version - 1.3.x) do not support header crc's, and will report that it is a "multi-part - gzip file" and give up. - - If deflateSetHeader is not used, the default gzip header has text false, - the time set to zero, and os set to 255, with no extra, name, or comment - fields. The gzip header is returned to the default state by deflateReset(). - - deflateSetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source - stream state was inconsistent. -*/ - -/* -ZEXTERN int ZEXPORT inflateInit2 OF((z_streamp strm, - int windowBits)); - - This is another version of inflateInit with an extra parameter. The - fields next_in, avail_in, zalloc, zfree and opaque must be initialized - before by the caller. - - The windowBits parameter is the base two logarithm of the maximum window - size (the size of the history buffer). It should be in the range 8..15 for - this version of the library. The default value is 15 if inflateInit is used - instead. windowBits must be greater than or equal to the windowBits value - provided to deflateInit2() while compressing, or it must be equal to 15 if - deflateInit2() was not used. If a compressed stream with a larger window - size is given as input, inflate() will return with the error code - Z_DATA_ERROR instead of trying to allocate a larger window. - - windowBits can also be -8..-15 for raw inflate. In this case, -windowBits - determines the window size. inflate() will then process raw deflate data, - not looking for a zlib or gzip header, not generating a check value, and not - looking for any check values for comparison at the end of the stream. This - is for use with other formats that use the deflate compressed data format - such as zip. Those formats provide their own check values. If a custom - format is developed using the raw deflate format for compressed data, it is - recommended that a check value such as an adler32 or a crc32 be applied to - the uncompressed data as is done in the zlib, gzip, and zip formats. For - most applications, the zlib format should be used as is. Note that comments - above on the use in deflateInit2() applies to the magnitude of windowBits. - - windowBits can also be greater than 15 for optional gzip decoding. Add - 32 to windowBits to enable zlib and gzip decoding with automatic header - detection, or add 16 to decode only the gzip format (the zlib format will - return a Z_DATA_ERROR). If a gzip stream is being decoded, strm->adler is - a crc32 instead of an adler32. - - inflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough - memory, Z_STREAM_ERROR if a parameter is invalid (such as a null strm). msg - is set to null if there is no error message. inflateInit2 does not perform - any decompression apart from reading the zlib header if present: this will - be done by inflate(). (So next_in and avail_in may be modified, but next_out - and avail_out are unchanged.) -*/ - -ZEXTERN int ZEXPORT inflateSetDictionary OF((z_streamp strm, - const Bytef *dictionary, - uInt dictLength)); -/* - Initializes the decompression dictionary from the given uncompressed byte - sequence. This function must be called immediately after a call of inflate, - if that call returned Z_NEED_DICT. The dictionary chosen by the compressor - can be determined from the adler32 value returned by that call of inflate. - The compressor and decompressor must use exactly the same dictionary (see - deflateSetDictionary). For raw inflate, this function can be called - immediately after inflateInit2() or inflateReset() and before any call of - inflate() to set the dictionary. The application must insure that the - dictionary that was used for compression is provided. - - inflateSetDictionary returns Z_OK if success, Z_STREAM_ERROR if a - parameter is invalid (such as NULL dictionary) or the stream state is - inconsistent, Z_DATA_ERROR if the given dictionary doesn't match the - expected one (incorrect adler32 value). inflateSetDictionary does not - perform any decompression: this will be done by subsequent calls of - inflate(). -*/ - -ZEXTERN int ZEXPORT inflateSync OF((z_streamp strm)); -/* - Skips invalid compressed data until a full flush point (see above the - description of deflate with Z_FULL_FLUSH) can be found, or until all - available input is skipped. No output is provided. - - inflateSync returns Z_OK if a full flush point has been found, Z_BUF_ERROR - if no more input was provided, Z_DATA_ERROR if no flush point has been found, - or Z_STREAM_ERROR if the stream structure was inconsistent. In the success - case, the application may save the current current value of total_in which - indicates where valid compressed data was found. In the error case, the - application may repeatedly call inflateSync, providing more input each time, - until success or end of the input data. -*/ - -ZEXTERN int ZEXPORT inflateCopy OF((z_streamp dest, - z_streamp source)); -/* - Sets the destination stream as a complete copy of the source stream. - - This function can be useful when randomly accessing a large stream. The - first pass through the stream can periodically record the inflate state, - allowing restarting inflate at those points when randomly accessing the - stream. - - inflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not - enough memory, Z_STREAM_ERROR if the source stream state was inconsistent - (such as zalloc being NULL). msg is left unchanged in both source and - destination. -*/ - -ZEXTERN int ZEXPORT inflateReset OF((z_streamp strm)); -/* - This function is equivalent to inflateEnd followed by inflateInit, - but does not free and reallocate all the internal decompression state. - The stream will keep attributes that may have been set by inflateInit2. - - inflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source - stream state was inconsistent (such as zalloc or state being NULL). -*/ - -ZEXTERN int ZEXPORT inflatePrime OF((z_streamp strm, - int bits, - int value)); -/* - This function inserts bits in the inflate input stream. The intent is - that this function is used to start inflating at a bit position in the - middle of a byte. The provided bits will be used before any bytes are used - from next_in. This function should only be used with raw inflate, and - should be used before the first inflate() call after inflateInit2() or - inflateReset(). bits must be less than or equal to 16, and that many of the - least significant bits of value will be inserted in the input. - - inflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source - stream state was inconsistent. -*/ - -ZEXTERN int ZEXPORT inflateGetHeader OF((z_streamp strm, - gz_headerp head)); -/* - inflateGetHeader() requests that gzip header information be stored in the - provided gz_header structure. inflateGetHeader() may be called after - inflateInit2() or inflateReset(), and before the first call of inflate(). - As inflate() processes the gzip stream, head->done is zero until the header - is completed, at which time head->done is set to one. If a zlib stream is - being decoded, then head->done is set to -1 to indicate that there will be - no gzip header information forthcoming. Note that Z_BLOCK can be used to - force inflate() to return immediately after header processing is complete - and before any actual data is decompressed. - - The text, time, xflags, and os fields are filled in with the gzip header - contents. hcrc is set to true if there is a header CRC. (The header CRC - was valid if done is set to one.) If extra is not Z_NULL, then extra_max - contains the maximum number of bytes to write to extra. Once done is true, - extra_len contains the actual extra field length, and extra contains the - extra field, or that field truncated if extra_max is less than extra_len. - If name is not Z_NULL, then up to name_max characters are written there, - terminated with a zero unless the length is greater than name_max. If - comment is not Z_NULL, then up to comm_max characters are written there, - terminated with a zero unless the length is greater than comm_max. When - any of extra, name, or comment are not Z_NULL and the respective field is - not present in the header, then that field is set to Z_NULL to signal its - absence. This allows the use of deflateSetHeader() with the returned - structure to duplicate the header. However if those fields are set to - allocated memory, then the application will need to save those pointers - elsewhere so that they can be eventually freed. - - If inflateGetHeader is not used, then the header information is simply - discarded. The header is always checked for validity, including the header - CRC if present. inflateReset() will reset the process to discard the header - information. The application would need to call inflateGetHeader() again to - retrieve the header from the next gzip stream. - - inflateGetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source - stream state was inconsistent. -*/ - -/* -ZEXTERN int ZEXPORT inflateBackInit OF((z_streamp strm, int windowBits, - unsigned char FAR *window)); - - Initialize the internal stream state for decompression using inflateBack() - calls. The fields zalloc, zfree and opaque in strm must be initialized - before the call. If zalloc and zfree are Z_NULL, then the default library- - derived memory allocation routines are used. windowBits is the base two - logarithm of the window size, in the range 8..15. window is a caller - supplied buffer of that size. Except for special applications where it is - assured that deflate was used with small window sizes, windowBits must be 15 - and a 32K byte window must be supplied to be able to decompress general - deflate streams. - - See inflateBack() for the usage of these routines. - - inflateBackInit will return Z_OK on success, Z_STREAM_ERROR if any of - the paramaters are invalid, Z_MEM_ERROR if the internal state could not - be allocated, or Z_VERSION_ERROR if the version of the library does not - match the version of the header file. -*/ - -typedef unsigned (*in_func) OF((void FAR *, unsigned char FAR * FAR *)); -typedef int (*out_func) OF((void FAR *, unsigned char FAR *, unsigned)); - -ZEXTERN int ZEXPORT inflateBack OF((z_streamp strm, - in_func in, void FAR *in_desc, - out_func out, void FAR *out_desc)); -/* - inflateBack() does a raw inflate with a single call using a call-back - interface for input and output. This is more efficient than inflate() for - file i/o applications in that it avoids copying between the output and the - sliding window by simply making the window itself the output buffer. This - function trusts the application to not change the output buffer passed by - the output function, at least until inflateBack() returns. - - inflateBackInit() must be called first to allocate the internal state - and to initialize the state with the user-provided window buffer. - inflateBack() may then be used multiple times to inflate a complete, raw - deflate stream with each call. inflateBackEnd() is then called to free - the allocated state. - - A raw deflate stream is one with no zlib or gzip header or trailer. - This routine would normally be used in a utility that reads zip or gzip - files and writes out uncompressed files. The utility would decode the - header and process the trailer on its own, hence this routine expects - only the raw deflate stream to decompress. This is different from the - normal behavior of inflate(), which expects either a zlib or gzip header and - trailer around the deflate stream. - - inflateBack() uses two subroutines supplied by the caller that are then - called by inflateBack() for input and output. inflateBack() calls those - routines until it reads a complete deflate stream and writes out all of the - uncompressed data, or until it encounters an error. The function's - parameters and return types are defined above in the in_func and out_func - typedefs. inflateBack() will call in(in_desc, &buf) which should return the - number of bytes of provided input, and a pointer to that input in buf. If - there is no input available, in() must return zero--buf is ignored in that - case--and inflateBack() will return a buffer error. inflateBack() will call - out(out_desc, buf, len) to write the uncompressed data buf[0..len-1]. out() - should return zero on success, or non-zero on failure. If out() returns - non-zero, inflateBack() will return with an error. Neither in() nor out() - are permitted to change the contents of the window provided to - inflateBackInit(), which is also the buffer that out() uses to write from. - The length written by out() will be at most the window size. Any non-zero - amount of input may be provided by in(). - - For convenience, inflateBack() can be provided input on the first call by - setting strm->next_in and strm->avail_in. If that input is exhausted, then - in() will be called. Therefore strm->next_in must be initialized before - calling inflateBack(). If strm->next_in is Z_NULL, then in() will be called - immediately for input. If strm->next_in is not Z_NULL, then strm->avail_in - must also be initialized, and then if strm->avail_in is not zero, input will - initially be taken from strm->next_in[0 .. strm->avail_in - 1]. - - The in_desc and out_desc parameters of inflateBack() is passed as the - first parameter of in() and out() respectively when they are called. These - descriptors can be optionally used to pass any information that the caller- - supplied in() and out() functions need to do their job. - - On return, inflateBack() will set strm->next_in and strm->avail_in to - pass back any unused input that was provided by the last in() call. The - return values of inflateBack() can be Z_STREAM_END on success, Z_BUF_ERROR - if in() or out() returned an error, Z_DATA_ERROR if there was a format - error in the deflate stream (in which case strm->msg is set to indicate the - nature of the error), or Z_STREAM_ERROR if the stream was not properly - initialized. In the case of Z_BUF_ERROR, an input or output error can be - distinguished using strm->next_in which will be Z_NULL only if in() returned - an error. If strm->next is not Z_NULL, then the Z_BUF_ERROR was due to - out() returning non-zero. (in() will always be called before out(), so - strm->next_in is assured to be defined if out() returns non-zero.) Note - that inflateBack() cannot return Z_OK. -*/ - -ZEXTERN int ZEXPORT inflateBackEnd OF((z_streamp strm)); -/* - All memory allocated by inflateBackInit() is freed. - - inflateBackEnd() returns Z_OK on success, or Z_STREAM_ERROR if the stream - state was inconsistent. -*/ - -ZEXTERN uLong ZEXPORT zlibCompileFlags OF((void)); -/* Return flags indicating compile-time options. - - Type sizes, two bits each, 00 = 16 bits, 01 = 32, 10 = 64, 11 = other: - 1.0: size of uInt - 3.2: size of uLong - 5.4: size of voidpf (pointer) - 7.6: size of z_off_t - - Compiler, assembler, and debug options: - 8: DEBUG - 9: ASMV or ASMINF -- use ASM code - 10: ZLIB_WINAPI -- exported functions use the WINAPI calling convention - 11: 0 (reserved) - - One-time table building (smaller code, but not thread-safe if true): - 12: BUILDFIXED -- build static block decoding tables when needed - 13: DYNAMIC_CRC_TABLE -- build CRC calculation tables when needed - 14,15: 0 (reserved) - - Library content (indicates missing functionality): - 16: NO_GZCOMPRESS -- gz* functions cannot compress (to avoid linking - deflate code when not needed) - 17: NO_GZIP -- deflate can't write gzip streams, and inflate can't detect - and decode gzip streams (to avoid linking crc code) - 18-19: 0 (reserved) - - Operation variations (changes in library functionality): - 20: PKZIP_BUG_WORKAROUND -- slightly more permissive inflate - 21: FASTEST -- deflate algorithm with only one, lowest compression level - 22,23: 0 (reserved) - - The sprintf variant used by gzprintf (zero is best): - 24: 0 = vs*, 1 = s* -- 1 means limited to 20 arguments after the format - 25: 0 = *nprintf, 1 = *printf -- 1 means gzprintf() not secure! - 26: 0 = returns value, 1 = void -- 1 means inferred string length returned - - Remainder: - 27-31: 0 (reserved) - */ - - - /* utility functions */ - -/* - The following utility functions are implemented on top of the - basic stream-oriented functions. To simplify the interface, some - default options are assumed (compression level and memory usage, - standard memory allocation functions). The source code of these - utility functions can easily be modified if you need special options. -*/ - -ZEXTERN int ZEXPORT compress OF((Bytef *dest, uLongf *destLen, - const Bytef *source, uLong sourceLen)); -/* - Compresses the source buffer into the destination buffer. sourceLen is - the byte length of the source buffer. Upon entry, destLen is the total - size of the destination buffer, which must be at least the value returned - by compressBound(sourceLen). Upon exit, destLen is the actual size of the - compressed buffer. - This function can be used to compress a whole file at once if the - input file is mmap'ed. - compress returns Z_OK if success, Z_MEM_ERROR if there was not - enough memory, Z_BUF_ERROR if there was not enough room in the output - buffer. -*/ - -ZEXTERN int ZEXPORT compress2 OF((Bytef *dest, uLongf *destLen, - const Bytef *source, uLong sourceLen, - int level)); -/* - Compresses the source buffer into the destination buffer. The level - parameter has the same meaning as in deflateInit. sourceLen is the byte - length of the source buffer. Upon entry, destLen is the total size of the - destination buffer, which must be at least the value returned by - compressBound(sourceLen). Upon exit, destLen is the actual size of the - compressed buffer. - - compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough - memory, Z_BUF_ERROR if there was not enough room in the output buffer, - Z_STREAM_ERROR if the level parameter is invalid. -*/ - -ZEXTERN uLong ZEXPORT compressBound OF((uLong sourceLen)); -/* - compressBound() returns an upper bound on the compressed size after - compress() or compress2() on sourceLen bytes. It would be used before - a compress() or compress2() call to allocate the destination buffer. -*/ - -ZEXTERN int ZEXPORT uncompress OF((Bytef *dest, uLongf *destLen, - const Bytef *source, uLong sourceLen)); -/* - Decompresses the source buffer into the destination buffer. sourceLen is - the byte length of the source buffer. Upon entry, destLen is the total - size of the destination buffer, which must be large enough to hold the - entire uncompressed data. (The size of the uncompressed data must have - been saved previously by the compressor and transmitted to the decompressor - by some mechanism outside the scope of this compression library.) - Upon exit, destLen is the actual size of the compressed buffer. - This function can be used to decompress a whole file at once if the - input file is mmap'ed. - - uncompress returns Z_OK if success, Z_MEM_ERROR if there was not - enough memory, Z_BUF_ERROR if there was not enough room in the output - buffer, or Z_DATA_ERROR if the input data was corrupted or incomplete. -*/ - - -typedef voidp gzFile; - -ZEXTERN gzFile ZEXPORT gzopen OF((const char *path, const char *mode)); -/* - Opens a gzip (.gz) file for reading or writing. The mode parameter - is as in fopen ("rb" or "wb") but can also include a compression level - ("wb9") or a strategy: 'f' for filtered data as in "wb6f", 'h' for - Huffman only compression as in "wb1h", or 'R' for run-length encoding - as in "wb1R". (See the description of deflateInit2 for more information - about the strategy parameter.) - - gzopen can be used to read a file which is not in gzip format; in this - case gzread will directly read from the file without decompression. - - gzopen returns NULL if the file could not be opened or if there was - insufficient memory to allocate the (de)compression state; errno - can be checked to distinguish the two cases (if errno is zero, the - zlib error is Z_MEM_ERROR). */ - -ZEXTERN gzFile ZEXPORT gzdopen OF((int fd, const char *mode)); -/* - gzdopen() associates a gzFile with the file descriptor fd. File - descriptors are obtained from calls like open, dup, creat, pipe or - fileno (in the file has been previously opened with fopen). - The mode parameter is as in gzopen. - The next call of gzclose on the returned gzFile will also close the - file descriptor fd, just like fclose(fdopen(fd), mode) closes the file - descriptor fd. If you want to keep fd open, use gzdopen(dup(fd), mode). - gzdopen returns NULL if there was insufficient memory to allocate - the (de)compression state. -*/ - -ZEXTERN int ZEXPORT gzsetparams OF((gzFile file, int level, int strategy)); -/* - Dynamically update the compression level or strategy. See the description - of deflateInit2 for the meaning of these parameters. - gzsetparams returns Z_OK if success, or Z_STREAM_ERROR if the file was not - opened for writing. -*/ - -ZEXTERN int ZEXPORT gzread OF((gzFile file, voidp buf, unsigned len)); -/* - Reads the given number of uncompressed bytes from the compressed file. - If the input file was not in gzip format, gzread copies the given number - of bytes into the buffer. - gzread returns the number of uncompressed bytes actually read (0 for - end of file, -1 for error). */ - -ZEXTERN int ZEXPORT gzwrite OF((gzFile file, - voidpc buf, unsigned len)); -/* - Writes the given number of uncompressed bytes into the compressed file. - gzwrite returns the number of uncompressed bytes actually written - (0 in case of error). -*/ - -ZEXTERN int ZEXPORTVA gzprintf OF((gzFile file, const char *format, ...)); -/* - Converts, formats, and writes the args to the compressed file under - control of the format string, as in fprintf. gzprintf returns the number of - uncompressed bytes actually written (0 in case of error). The number of - uncompressed bytes written is limited to 4095. The caller should assure that - this limit is not exceeded. If it is exceeded, then gzprintf() will return - return an error (0) with nothing written. In this case, there may also be a - buffer overflow with unpredictable consequences, which is possible only if - zlib was compiled with the insecure functions sprintf() or vsprintf() - because the secure snprintf() or vsnprintf() functions were not available. -*/ - -ZEXTERN int ZEXPORT gzputs OF((gzFile file, const char *s)); -/* - Writes the given null-terminated string to the compressed file, excluding - the terminating null character. - gzputs returns the number of characters written, or -1 in case of error. -*/ - -ZEXTERN char * ZEXPORT gzgets OF((gzFile file, char *buf, int len)); -/* - Reads bytes from the compressed file until len-1 characters are read, or - a newline character is read and transferred to buf, or an end-of-file - condition is encountered. The string is then terminated with a null - character. - gzgets returns buf, or Z_NULL in case of error. -*/ - -ZEXTERN int ZEXPORT gzputc OF((gzFile file, int c)); -/* - Writes c, converted to an unsigned char, into the compressed file. - gzputc returns the value that was written, or -1 in case of error. -*/ - -ZEXTERN int ZEXPORT gzgetc OF((gzFile file)); -/* - Reads one byte from the compressed file. gzgetc returns this byte - or -1 in case of end of file or error. -*/ - -ZEXTERN int ZEXPORT gzungetc OF((int c, gzFile file)); -/* - Push one character back onto the stream to be read again later. - Only one character of push-back is allowed. gzungetc() returns the - character pushed, or -1 on failure. gzungetc() will fail if a - character has been pushed but not read yet, or if c is -1. The pushed - character will be discarded if the stream is repositioned with gzseek() - or gzrewind(). -*/ - -ZEXTERN int ZEXPORT gzflush OF((gzFile file, int flush)); -/* - Flushes all pending output into the compressed file. The parameter - flush is as in the deflate() function. The return value is the zlib - error number (see function gzerror below). gzflush returns Z_OK if - the flush parameter is Z_FINISH and all output could be flushed. - gzflush should be called only when strictly necessary because it can - degrade compression. -*/ - -ZEXTERN z_off_t ZEXPORT gzseek OF((gzFile file, - z_off_t offset, int whence)); -/* - Sets the starting position for the next gzread or gzwrite on the - given compressed file. The offset represents a number of bytes in the - uncompressed data stream. The whence parameter is defined as in lseek(2); - the value SEEK_END is not supported. - If the file is opened for reading, this function is emulated but can be - extremely slow. If the file is opened for writing, only forward seeks are - supported; gzseek then compresses a sequence of zeroes up to the new - starting position. - - gzseek returns the resulting offset location as measured in bytes from - the beginning of the uncompressed stream, or -1 in case of error, in - particular if the file is opened for writing and the new starting position - would be before the current position. -*/ - -ZEXTERN int ZEXPORT gzrewind OF((gzFile file)); -/* - Rewinds the given file. This function is supported only for reading. - - gzrewind(file) is equivalent to (int)gzseek(file, 0L, SEEK_SET) -*/ - -ZEXTERN z_off_t ZEXPORT gztell OF((gzFile file)); -/* - Returns the starting position for the next gzread or gzwrite on the - given compressed file. This position represents a number of bytes in the - uncompressed data stream. - - gztell(file) is equivalent to gzseek(file, 0L, SEEK_CUR) -*/ - -ZEXTERN int ZEXPORT gzeof OF((gzFile file)); -/* - Returns 1 when EOF has previously been detected reading the given - input stream, otherwise zero. -*/ - -ZEXTERN int ZEXPORT gzdirect OF((gzFile file)); -/* - Returns 1 if file is being read directly without decompression, otherwise - zero. -*/ - -ZEXTERN int ZEXPORT gzclose OF((gzFile file)); -/* - Flushes all pending output if necessary, closes the compressed file - and deallocates all the (de)compression state. The return value is the zlib - error number (see function gzerror below). -*/ - -ZEXTERN const char * ZEXPORT gzerror OF((gzFile file, int *errnum)); -/* - Returns the error message for the last error which occurred on the - given compressed file. errnum is set to zlib error number. If an - error occurred in the file system and not in the compression library, - errnum is set to Z_ERRNO and the application may consult errno - to get the exact error code. -*/ - -ZEXTERN void ZEXPORT gzclearerr OF((gzFile file)); -/* - Clears the error and end-of-file flags for file. This is analogous to the - clearerr() function in stdio. This is useful for continuing to read a gzip - file that is being written concurrently. -*/ - - /* checksum functions */ - -/* - These functions are not related to compression but are exported - anyway because they might be useful in applications using the - compression library. -*/ - -ZEXTERN uLong ZEXPORT adler32 OF((uLong adler, const Bytef *buf, uInt len)); -/* - Update a running Adler-32 checksum with the bytes buf[0..len-1] and - return the updated checksum. If buf is NULL, this function returns - the required initial value for the checksum. - An Adler-32 checksum is almost as reliable as a CRC32 but can be computed - much faster. Usage example: - - uLong adler = adler32(0L, Z_NULL, 0); - - while (read_buffer(buffer, length) != EOF) { - adler = adler32(adler, buffer, length); - } - if (adler != original_adler) error(); -*/ - -ZEXTERN uLong ZEXPORT adler32_combine OF((uLong adler1, uLong adler2, - z_off_t len2)); -/* - Combine two Adler-32 checksums into one. For two sequences of bytes, seq1 - and seq2 with lengths len1 and len2, Adler-32 checksums were calculated for - each, adler1 and adler2. adler32_combine() returns the Adler-32 checksum of - seq1 and seq2 concatenated, requiring only adler1, adler2, and len2. -*/ - -ZEXTERN uLong ZEXPORT crc32 OF((uLong crc, const Bytef *buf, uInt len)); -/* - Update a running CRC-32 with the bytes buf[0..len-1] and return the - updated CRC-32. If buf is NULL, this function returns the required initial - value for the for the crc. Pre- and post-conditioning (one's complement) is - performed within this function so it shouldn't be done by the application. - Usage example: - - uLong crc = crc32(0L, Z_NULL, 0); - - while (read_buffer(buffer, length) != EOF) { - crc = crc32(crc, buffer, length); - } - if (crc != original_crc) error(); -*/ - -ZEXTERN uLong ZEXPORT crc32_combine OF((uLong crc1, uLong crc2, z_off_t len2)); - -/* - Combine two CRC-32 check values into one. For two sequences of bytes, - seq1 and seq2 with lengths len1 and len2, CRC-32 check values were - calculated for each, crc1 and crc2. crc32_combine() returns the CRC-32 - check value of seq1 and seq2 concatenated, requiring only crc1, crc2, and - len2. -*/ - - - /* various hacks, don't look :) */ - -/* deflateInit and inflateInit are macros to allow checking the zlib version - * and the compiler's view of z_stream: - */ -ZEXTERN int ZEXPORT deflateInit_ OF((z_streamp strm, int level, - const char *version, int stream_size)); -ZEXTERN int ZEXPORT inflateInit_ OF((z_streamp strm, - const char *version, int stream_size)); -ZEXTERN int ZEXPORT deflateInit2_ OF((z_streamp strm, int level, int method, - int windowBits, int memLevel, - int strategy, const char *version, - int stream_size)); -ZEXTERN int ZEXPORT inflateInit2_ OF((z_streamp strm, int windowBits, - const char *version, int stream_size)); -ZEXTERN int ZEXPORT inflateBackInit_ OF((z_streamp strm, int windowBits, - unsigned char FAR *window, - const char *version, - int stream_size)); -#define deflateInit(strm, level) \ - deflateInit_((strm), (level), ZLIB_VERSION, sizeof(z_stream)) -#define inflateInit(strm) \ - inflateInit_((strm), ZLIB_VERSION, sizeof(z_stream)) -#define deflateInit2(strm, level, method, windowBits, memLevel, strategy) \ - deflateInit2_((strm),(level),(method),(windowBits),(memLevel),\ - (strategy), ZLIB_VERSION, sizeof(z_stream)) -#define inflateInit2(strm, windowBits) \ - inflateInit2_((strm), (windowBits), ZLIB_VERSION, sizeof(z_stream)) -#define inflateBackInit(strm, windowBits, window) \ - inflateBackInit_((strm), (windowBits), (window), \ - ZLIB_VERSION, sizeof(z_stream)) - - -#if !defined(ZUTIL_H) && !defined(NO_DUMMY_DECL) - struct internal_state {int dummy;}; /* hack for buggy compilers */ -#endif - -ZEXTERN const char * ZEXPORT zError OF((int)); -ZEXTERN int ZEXPORT inflateSyncPoint OF((z_streamp z)); -ZEXTERN const uLongf * ZEXPORT get_crc_table OF((void)); - -#ifdef __cplusplus -} -#endif - -#endif /* ZLIB_H */ diff --git a/sourcepawn/third_party/zlib/zutil.c b/sourcepawn/third_party/zlib/zutil.c deleted file mode 100644 index 56e552f4..00000000 --- a/sourcepawn/third_party/zlib/zutil.c +++ /dev/null @@ -1,319 +0,0 @@ -/* zutil.c -- target dependent utility functions for the compression library - * Copyright (C) 1995-2005 Jean-loup Gailly. - * For conditions of distribution and use, see copyright notice in zlib.h - */ - -/* @(#) $Id$ */ - -#include -#include "zutil.h" - -#ifndef NO_DUMMY_DECL -struct internal_state {int dummy;}; /* for buggy compilers */ -#endif - -const char * const z_errmsg[10] = { -"need dictionary", /* Z_NEED_DICT 2 */ -"stream end", /* Z_STREAM_END 1 */ -"", /* Z_OK 0 */ -"file error", /* Z_ERRNO (-1) */ -"stream error", /* Z_STREAM_ERROR (-2) */ -"data error", /* Z_DATA_ERROR (-3) */ -"insufficient memory", /* Z_MEM_ERROR (-4) */ -"buffer error", /* Z_BUF_ERROR (-5) */ -"incompatible version",/* Z_VERSION_ERROR (-6) */ -""}; - - -const char * ZEXPORT zlibVersion() -{ - return ZLIB_VERSION; -} - -uLong ZEXPORT zlibCompileFlags() -{ - uLong flags; - - flags = 0; - switch (sizeof(uInt)) { - case 2: break; - case 4: flags += 1; break; - case 8: flags += 2; break; - default: flags += 3; - } - switch (sizeof(uLong)) { - case 2: break; - case 4: flags += 1 << 2; break; - case 8: flags += 2 << 2; break; - default: flags += 3 << 2; - } - switch (sizeof(voidpf)) { - case 2: break; - case 4: flags += 1 << 4; break; - case 8: flags += 2 << 4; break; - default: flags += 3 << 4; - } - switch (sizeof(z_off_t)) { - case 2: break; - case 4: flags += 1 << 6; break; - case 8: flags += 2 << 6; break; - default: flags += 3 << 6; - } -#ifdef DEBUG - flags += 1 << 8; -#endif -#if defined(ASMV) || defined(ASMINF) - flags += 1 << 9; -#endif -#ifdef ZLIB_WINAPI - flags += 1 << 10; -#endif -#ifdef BUILDFIXED - flags += 1 << 12; -#endif -#ifdef DYNAMIC_CRC_TABLE - flags += 1 << 13; -#endif -#ifdef NO_GZCOMPRESS - flags += 1L << 16; -#endif -#ifdef NO_GZIP - flags += 1L << 17; -#endif -#ifdef PKZIP_BUG_WORKAROUND - flags += 1L << 20; -#endif -#ifdef FASTEST - flags += 1L << 21; -#endif -#ifdef STDC -# ifdef NO_vsnprintf - flags += 1L << 25; -# ifdef HAS_vsprintf_void - flags += 1L << 26; -# endif -# else -# ifdef HAS_vsnprintf_void - flags += 1L << 26; -# endif -# endif -#else - flags += 1L << 24; -# ifdef NO_snprintf - flags += 1L << 25; -# ifdef HAS_sprintf_void - flags += 1L << 26; -# endif -# else -# ifdef HAS_snprintf_void - flags += 1L << 26; -# endif -# endif -#endif - return flags; -} - -#ifdef DEBUG - -# ifndef verbose -# define verbose 0 -# endif -int z_verbose = verbose; - -void z_error (m) - char *m; -{ - fprintf(stderr, "%s\n", m); - exit(1); -} -#endif - -/* exported to allow conversion of error code to string for compress() and - * uncompress() - */ -const char * ZEXPORT zError(err) - int err; -{ - return ERR_MSG(err); -} - -#if defined(_WIN32_WCE) - /* The Microsoft C Run-Time Library for Windows CE doesn't have - * errno. We define it as a global variable to simplify porting. - * Its value is always 0 and should not be used. - */ - int errno = 0; -#endif - -#ifndef HAVE_MEMCPY - -void zmemcpy(dest, source, len) - Bytef* dest; - const Bytef* source; - uInt len; -{ - if (len == 0) return; - do { - *dest++ = *source++; /* ??? to be unrolled */ - } while (--len != 0); -} - -int zmemcmp(s1, s2, len) - const Bytef* s1; - const Bytef* s2; - uInt len; -{ - uInt j; - - for (j = 0; j < len; j++) { - if (s1[j] != s2[j]) return 2*(s1[j] > s2[j])-1; - } - return 0; -} - -void zmemzero(dest, len) - Bytef* dest; - uInt len; -{ - if (len == 0) return; - do { - *dest++ = 0; /* ??? to be unrolled */ - } while (--len != 0); -} -#endif - - -#ifdef SYS16BIT - -#ifdef __TURBOC__ -/* Turbo C in 16-bit mode */ - -# define MY_ZCALLOC - -/* Turbo C malloc() does not allow dynamic allocation of 64K bytes - * and farmalloc(64K) returns a pointer with an offset of 8, so we - * must fix the pointer. Warning: the pointer must be put back to its - * original form in order to free it, use zcfree(). - */ - -#define MAX_PTR 10 -/* 10*64K = 640K */ - -local int next_ptr = 0; - -typedef struct ptr_table_s { - voidpf org_ptr; - voidpf new_ptr; -} ptr_table; - -local ptr_table table[MAX_PTR]; -/* This table is used to remember the original form of pointers - * to large buffers (64K). Such pointers are normalized with a zero offset. - * Since MSDOS is not a preemptive multitasking OS, this table is not - * protected from concurrent access. This hack doesn't work anyway on - * a protected system like OS/2. Use Microsoft C instead. - */ - -voidpf zcalloc (voidpf opaque, unsigned items, unsigned size) -{ - voidpf buf = opaque; /* just to make some compilers happy */ - ulg bsize = (ulg)items*size; - - /* If we allocate less than 65520 bytes, we assume that farmalloc - * will return a usable pointer which doesn't have to be normalized. - */ - if (bsize < 65520L) { - buf = farmalloc(bsize); - if (*(ush*)&buf != 0) return buf; - } else { - buf = farmalloc(bsize + 16L); - } - if (buf == NULL || next_ptr >= MAX_PTR) return NULL; - table[next_ptr].org_ptr = buf; - - /* Normalize the pointer to seg:0 */ - *((ush*)&buf+1) += ((ush)((uch*)buf-0) + 15) >> 4; - *(ush*)&buf = 0; - table[next_ptr++].new_ptr = buf; - return buf; -} - -void zcfree (voidpf opaque, voidpf ptr) -{ - int n; - if (*(ush*)&ptr != 0) { /* object < 64K */ - farfree(ptr); - return; - } - /* Find the original pointer */ - for (n = 0; n < next_ptr; n++) { - if (ptr != table[n].new_ptr) continue; - - farfree(table[n].org_ptr); - while (++n < next_ptr) { - table[n-1] = table[n]; - } - next_ptr--; - return; - } - ptr = opaque; /* just to make some compilers happy */ - Assert(0, "zcfree: ptr not found"); -} - -#endif /* __TURBOC__ */ - - -#ifdef M_I86 -/* Microsoft C in 16-bit mode */ - -# define MY_ZCALLOC - -#if (!defined(_MSC_VER) || (_MSC_VER <= 600)) -# define _halloc halloc -# define _hfree hfree -#endif - -voidpf zcalloc (voidpf opaque, unsigned items, unsigned size) -{ - if (opaque) opaque = 0; /* to make compiler happy */ - return _halloc((long)items, size); -} - -void zcfree (voidpf opaque, voidpf ptr) -{ - if (opaque) opaque = 0; /* to make compiler happy */ - _hfree(ptr); -} - -#endif /* M_I86 */ - -#endif /* SYS16BIT */ - - -#ifndef MY_ZCALLOC /* Any system without a special alloc function */ - -#ifndef STDC -extern voidp malloc OF((uInt size)); -extern voidp calloc OF((uInt items, uInt size)); -extern void free OF((voidpf ptr)); -#endif - -voidpf zcalloc (opaque, items, size) - voidpf opaque; - unsigned items; - unsigned size; -{ - if (opaque) items += size - size; /* make compiler happy */ - return sizeof(uInt) > 2 ? (voidpf)malloc(items * size) : - (voidpf)calloc(items, size); -} - -void zcfree (opaque, ptr) - voidpf opaque; - voidpf ptr; -{ - free(ptr); - if (opaque) return; /* make compiler happy */ -} - -#endif /* MY_ZCALLOC */ diff --git a/sourcepawn/third_party/zlib/zutil.h b/sourcepawn/third_party/zlib/zutil.h deleted file mode 100644 index 0ba6e020..00000000 --- a/sourcepawn/third_party/zlib/zutil.h +++ /dev/null @@ -1,269 +0,0 @@ -/* zutil.h -- internal interface and configuration of the compression library - * Copyright (C) 1995-2005 Jean-loup Gailly. - * For conditions of distribution and use, see copyright notice in zlib.h - */ - -/* WARNING: this file should *not* be used by applications. It is - part of the implementation of the compression library and is - subject to change. Applications should only use zlib.h. - */ - -/* @(#) $Id$ */ - -#ifndef ZUTIL_H -#define ZUTIL_H - -#define ZLIB_INTERNAL -#include "zlib.h" - -#ifdef STDC -# ifndef _WIN32_WCE -# include -# endif -# include -# include -#endif -#ifdef NO_ERRNO_H -# ifdef _WIN32_WCE - /* The Microsoft C Run-Time Library for Windows CE doesn't have - * errno. We define it as a global variable to simplify porting. - * Its value is always 0 and should not be used. We rename it to - * avoid conflict with other libraries that use the same workaround. - */ -# define errno z_errno -# endif - extern int errno; -#else -# ifndef _WIN32_WCE -# include -# endif -#endif - -#ifndef local -# define local static -#endif -/* compile with -Dlocal if your debugger can't find static symbols */ - -typedef unsigned char uch; -typedef uch FAR uchf; -typedef unsigned short ush; -typedef ush FAR ushf; -typedef unsigned long ulg; - -extern const char * const z_errmsg[10]; /* indexed by 2-zlib_error */ -/* (size given to avoid silly warnings with Visual C++) */ - -#define ERR_MSG(err) z_errmsg[Z_NEED_DICT-(err)] - -#define ERR_RETURN(strm,err) \ - return (strm->msg = (char*)ERR_MSG(err), (err)) -/* To be used only when the state is known to be valid */ - - /* common constants */ - -#ifndef DEF_WBITS -# define DEF_WBITS MAX_WBITS -#endif -/* default windowBits for decompression. MAX_WBITS is for compression only */ - -#if MAX_MEM_LEVEL >= 8 -# define DEF_MEM_LEVEL 8 -#else -# define DEF_MEM_LEVEL MAX_MEM_LEVEL -#endif -/* default memLevel */ - -#define STORED_BLOCK 0 -#define STATIC_TREES 1 -#define DYN_TREES 2 -/* The three kinds of block type */ - -#define MIN_MATCH 3 -#define MAX_MATCH 258 -/* The minimum and maximum match lengths */ - -#define PRESET_DICT 0x20 /* preset dictionary flag in zlib header */ - - /* target dependencies */ - -#if defined(MSDOS) || (defined(WINDOWS) && !defined(WIN32)) -# define OS_CODE 0x00 -# if defined(__TURBOC__) || defined(__BORLANDC__) -# if(__STDC__ == 1) && (defined(__LARGE__) || defined(__COMPACT__)) - /* Allow compilation with ANSI keywords only enabled */ - void _Cdecl farfree( void *block ); - void *_Cdecl farmalloc( unsigned long nbytes ); -# else -# include -# endif -# else /* MSC or DJGPP */ -# include -# endif -#endif - -#ifdef AMIGA -# define OS_CODE 0x01 -#endif - -#if defined(VAXC) || defined(VMS) -# define OS_CODE 0x02 -# define F_OPEN(name, mode) \ - fopen((name), (mode), "mbc=60", "ctx=stm", "rfm=fix", "mrs=512") -#endif - -#if defined(ATARI) || defined(atarist) -# define OS_CODE 0x05 -#endif - -#ifdef OS2 -# define OS_CODE 0x06 -# ifdef M_I86 - #include -# endif -#endif - -#if defined(MACOS) || defined(TARGET_OS_MAC) -# define OS_CODE 0x07 -# if defined(__MWERKS__) && __dest_os != __be_os && __dest_os != __win32_os -# include /* for fdopen */ -# else -# ifndef fdopen -# define fdopen(fd,mode) NULL /* No fdopen() */ -# endif -# endif -#endif - -#ifdef TOPS20 -# define OS_CODE 0x0a -#endif - -#ifdef WIN32 -# ifndef __CYGWIN__ /* Cygwin is Unix, not Win32 */ -# define OS_CODE 0x0b -# endif -#endif - -#ifdef __50SERIES /* Prime/PRIMOS */ -# define OS_CODE 0x0f -#endif - -#if defined(_BEOS_) || defined(RISCOS) -# define fdopen(fd,mode) NULL /* No fdopen() */ -#endif - -#if (defined(_MSC_VER) && (_MSC_VER > 600)) -# if defined(_WIN32_WCE) -# define fdopen(fd,mode) NULL /* No fdopen() */ -# ifndef _PTRDIFF_T_DEFINED - typedef int ptrdiff_t; -# define _PTRDIFF_T_DEFINED -# endif -# else -# define fdopen(fd,type) _fdopen(fd,type) -# endif -#endif - - /* common defaults */ - -#ifndef OS_CODE -# define OS_CODE 0x03 /* assume Unix */ -#endif - -#ifndef F_OPEN -# define F_OPEN(name, mode) fopen((name), (mode)) -#endif - - /* functions */ - -#if defined(STDC99) || (defined(__TURBOC__) && __TURBOC__ >= 0x550) -# ifndef HAVE_VSNPRINTF -# define HAVE_VSNPRINTF -# endif -#endif -#if defined(__CYGWIN__) -# ifndef HAVE_VSNPRINTF -# define HAVE_VSNPRINTF -# endif -#endif -#ifndef HAVE_VSNPRINTF -# ifdef MSDOS - /* vsnprintf may exist on some MS-DOS compilers (DJGPP?), - but for now we just assume it doesn't. */ -# define NO_vsnprintf -# endif -# ifdef __TURBOC__ -# define NO_vsnprintf -# endif -# ifdef WIN32 - /* In Win32, vsnprintf is available as the "non-ANSI" _vsnprintf. */ -# if !defined(vsnprintf) && !defined(NO_vsnprintf) -# define vsnprintf _vsnprintf -# endif -# endif -# ifdef __SASC -# define NO_vsnprintf -# endif -#endif -#ifdef VMS -# define NO_vsnprintf -#endif - -#if defined(pyr) -# define NO_MEMCPY -#endif -#if defined(SMALL_MEDIUM) && !defined(_MSC_VER) && !defined(__SC__) - /* Use our own functions for small and medium model with MSC <= 5.0. - * You may have to use the same strategy for Borland C (untested). - * The __SC__ check is for Symantec. - */ -# define NO_MEMCPY -#endif -#if defined(STDC) && !defined(HAVE_MEMCPY) && !defined(NO_MEMCPY) -# define HAVE_MEMCPY -#endif -#ifdef HAVE_MEMCPY -# ifdef SMALL_MEDIUM /* MSDOS small or medium model */ -# define zmemcpy _fmemcpy -# define zmemcmp _fmemcmp -# define zmemzero(dest, len) _fmemset(dest, 0, len) -# else -# define zmemcpy memcpy -# define zmemcmp memcmp -# define zmemzero(dest, len) memset(dest, 0, len) -# endif -#else - extern void zmemcpy OF((Bytef* dest, const Bytef* source, uInt len)); - extern int zmemcmp OF((const Bytef* s1, const Bytef* s2, uInt len)); - extern void zmemzero OF((Bytef* dest, uInt len)); -#endif - -/* Diagnostic functions */ -#ifdef DEBUG -# include - extern int z_verbose; - extern void z_error OF((char *m)); -# define Assert(cond,msg) {if(!(cond)) z_error(msg);} -# define Trace(x) {if (z_verbose>=0) fprintf x ;} -# define Tracev(x) {if (z_verbose>0) fprintf x ;} -# define Tracevv(x) {if (z_verbose>1) fprintf x ;} -# define Tracec(c,x) {if (z_verbose>0 && (c)) fprintf x ;} -# define Tracecv(c,x) {if (z_verbose>1 && (c)) fprintf x ;} -#else -# define Assert(cond,msg) -# define Trace(x) -# define Tracev(x) -# define Tracevv(x) -# define Tracec(c,x) -# define Tracecv(c,x) -#endif - - -voidpf zcalloc OF((voidpf opaque, unsigned items, unsigned size)); -void zcfree OF((voidpf opaque, voidpf ptr)); - -#define ZALLOC(strm, items, size) \ - (*((strm)->zalloc))((strm)->opaque, (items), (size)) -#define ZFREE(strm, addr) (*((strm)->zfree))((strm)->opaque, (voidpf)(addr)) -#define TRY_FREE(s, p) {if (p) ZFREE(s, p);} - -#endif /* ZUTIL_H */ diff --git a/sourcepawn/vm/AMBuilder b/sourcepawn/vm/AMBuilder deleted file mode 100644 index 363f8910..00000000 --- a/sourcepawn/vm/AMBuilder +++ /dev/null @@ -1,94 +0,0 @@ -# vim: set sts=2 ts=8 sw=2 tw=99 et ft=python: -import os - -Includes = [ - os.path.join(SM.mms_root, 'core', 'sourcehook'), - os.path.join(builder.currentSourcePath), - os.path.join(builder.currentSourcePath, '..', 'third_party'), - os.path.join(builder.sourcePath, 'public'), - os.path.join(builder.sourcePath, 'public', 'sourcepawn'), - os.path.join(builder.sourcePath, 'public', 'amtl', 'include'), - os.path.join(builder.sourcePath, 'public', 'jit'), - os.path.join(builder.sourcePath, 'public', 'jit', 'x86'), - - # The include path for SP v2 stuff. - os.path.join(builder.sourcePath, 'sourcepawn', 'include'), -] - -def setup(binary): - compiler = binary.compiler - compiler.includes += Includes - if compiler.vendor == 'gcc' or compiler.vendor == 'clang': - compiler.cxxflags += [ - '-fno-rtti', - '-Wno-invalid-offsetof', - ] - elif binary.compiler.vendor == 'msvc': - compiler.cxxflags += ['/GR-'] - - if binary.compiler.cc.behavior == 'msvc': - compiler.cxxflags.remove('/TP') - return binary - -# Build the static library. -library = setup(builder.compiler.StaticLibrary('sourcepawn')) -library.sources += [ - 'api.cpp', - 'code-allocator.cpp', - 'code-stubs.cpp', - 'compiled-function.cpp', - 'environment.cpp', - 'file-utils.cpp', - 'md5/md5.cpp', - 'opcodes.cpp', - 'plugin-context.cpp', - 'plugin-runtime.cpp', - 'scripted-invoker.cpp', - 'stack-frames.cpp', - 'smx-v1-image.cpp', - 'watchdog_timer.cpp', - 'x86/assembler-x86.cpp', - 'x86/code-stubs-x86.cpp', - 'x86/jit_x86.cpp', - 'x86/x86-utils.cpp', - '../third_party/zlib/adler32.c', - '../third_party/zlib/compress.c', - '../third_party/zlib/crc32.c', - '../third_party/zlib/deflate.c', - '../third_party/zlib/gzio.c', - '../third_party/zlib/infback.c', - '../third_party/zlib/inffast.c', - '../third_party/zlib/inflate.c', - '../third_party/zlib/inftrees.c', - '../third_party/zlib/trees.c', - '../third_party/zlib/uncompr.c', - '../third_party/zlib/zutil.c', -] -libsourcepawn = builder.Add(library).binary - -# Build the dynamically-linked library. -dll = setup(SM.Library(builder, 'sourcepawn.jit.x86')) -dll.compiler.linkflags[0:0] = [libsourcepawn] -dll.sources += [ - 'dll_exports.cpp' -] - -if builder.target_platform == 'linux': - dll.compiler.postlink += ['-lpthread', '-lrt'] - -SM.binaries += [builder.Add(dll)] - -# Build the debug shell. -shell = setup(SM.Program(builder, 'spshell')) -shell.compiler.defines += ['SPSHELL'] -shell.compiler.linkflags[0:0] = [libsourcepawn] -shell.sources += [ - 'dll_exports.cpp' -] -if shell.compiler.cc.behavior == 'msvc': - shell.compiler.linkflags.remove('/SUBSYSTEM:WINDOWS') - shell.compiler.linkflags.append('/SUBSYSTEM:CONSOLE') - -if builder.target_platform == 'linux': - shell.compiler.postlink += ['-lpthread', '-lrt'] -builder.Add(shell) diff --git a/sourcepawn/vm/Makefile b/sourcepawn/vm/Makefile deleted file mode 100644 index edc3368c..00000000 --- a/sourcepawn/vm/Makefile +++ /dev/null @@ -1,119 +0,0 @@ -# (C)2004-2008 SourceMod Development Team -# Makefile written by David "BAILOPAN" Anderson - -SMSDK = ../.. -MMSOURCE17 = ../../../mmsource-1.7 - -##################################### -### EDIT BELOW FOR OTHER PROJECTS ### -##################################### - -PROJECT = sourcepawn.jit.x86 - -OBJECTS = dll_exports.cpp \ - environment.cpp \ - x86/jit_x86.cpp \ - sp_vm_basecontext.cpp \ - sp_vm_engine.cpp \ - scripted-invoker.cpp \ - engine2.cpp \ - plugin-runtime.cpp \ - opcodes.cpp \ - compiled-function.cpp \ - md5/md5.cpp \ - zlib/adler32.c \ - zlib/compress.c \ - zlib/crc32.c \ - zlib/deflate.c \ - zlib/gzio.c \ - zlib/infback.c \ - zlib/inffast.c \ - zlib/inflate.c \ - zlib/inftrees.c \ - zlib/trees.c \ - zlib/uncompr.c \ - zlib/zutil.c \ - -OBJECTS += ../../knight/shared/KeCodeAllocator.cpp - -############################################## -### CONFIGURE ANY OTHER FLAGS/OPTIONS HERE ### -############################################## - -C_OPT_FLAGS = -DNDEBUG -O3 -funroll-loops -pipe -fno-strict-aliasing -C_DEBUG_FLAGS = -D_DEBUG -DDEBUG -g -ggdb3 -C_GCC4_FLAGS = -fvisibility=hidden -CPP_GCC4_FLAGS = -fvisibility-inlines-hidden -CPP = gcc - -LINK = -m32 -ldl -lm - -INCLUDE = -I. -I.. -I$(SMSDK)/public -I$(SMSDK)/public/jit -I$(SMSDK)/public/jit/x86 \ - -I$(SMSDK)/public/sourcepawn -I$(MMSOURCE17)/core/sourcehook -I$(SMSDK)/knight/shared -Ix86 - -CFLAGS += -D_LINUX -Dstricmp=strcasecmp -D_stricmp=strcasecmp -D_strnicmp=strncasecmp -Dstrnicmp=strncasecmp \ - -D_snprintf=snprintf -D_vsnprintf=vsnprintf -D_alloca=alloca -Dstrcmpi=strcasecmp -Wall -DHAVE_STDINT_H \ - -m32 -Wno-uninitialized -Werror -CPPFLAGS += -Wno-non-virtual-dtor -fno-exceptions -fno-rtti - -################################################ -### DO NOT EDIT BELOW HERE FOR MOST PROJECTS ### -################################################ - -ifeq "$(DEBUG)" "true" - BIN_DIR = Debug - CFLAGS += $(C_DEBUG_FLAGS) -else - BIN_DIR = Release - CFLAGS += $(C_OPT_FLAGS) -endif - -OS := $(shell uname -s) -ifeq "$(OS)" "Darwin" - LINK += -dynamiclib - BINARY = $(PROJECT).dylib -else - LINK += -static-libgcc -shared - BINARY = $(PROJECT).so -endif - -GCC_VERSION := $(shell $(CPP) -dumpversion >&1 | cut -b1) -ifeq "$(GCC_VERSION)" "4" - CFLAGS += $(C_GCC4_FLAGS) - CPPFLAGS += $(CPP_GCC4_FLAGS) -endif - -OBJ_LINUX := $(OBJECTS:../../knight/shared/%.cpp=$(BIN_DIR)/knight/%.o) -OBJ_LINUX := $(OBJ_LINUX:%.cpp=$(BIN_DIR)/%.o) -OBJ_LINUX := $(OBJ_LINUX:%.c=$(BIN_DIR)/%.o) - -default: all - -$(BIN_DIR)/%.o: %.c - $(CPP) $(INCLUDE) $(CFLAGS) -o $@ -c $< - -$(BIN_DIR)/%.o: %.cpp - $(CPP) $(INCLUDE) $(CFLAGS) $(CPPFLAGS) -o $@ -c $< - -$(BIN_DIR)/knight/%.o: ../../knight/shared/%.cpp - $(CPP) $(INCLUDE) $(CFLAGS) $(CPPFLAGS) -o $@ -c $< - -all: - mkdir -p $(BIN_DIR)/x86 - mkdir -p $(BIN_DIR)/zlib - mkdir -p $(BIN_DIR)/knight - $(MAKE) -f Makefile jit - -jit: $(OBJ_LINUX) - $(CPP) $(INCLUDE) $(OBJ_LINUX) $(LINK) -o $(BIN_DIR)/$(BINARY) - -debug: - $(MAKE) -f Makefile all DEBUG=true - -clean: - rm -rf $(BIN_DIR)/x86/*.o - rm -rf $(BIN_DIR)/zlib/*.o - rm -rf $(BIN_DIR)/knight/*.o - rm -rf $(BIN_DIR)/*.o - rm -rf $(BIN_DIR)/$(BINARY) - diff --git a/sourcepawn/vm/Makefile.shell b/sourcepawn/vm/Makefile.shell deleted file mode 100644 index b1509d0c..00000000 --- a/sourcepawn/vm/Makefile.shell +++ /dev/null @@ -1,120 +0,0 @@ -# (C)2004-2008 SourceMod Development Team -# Makefile written by David "BAILOPAN" Anderson - -SMSDK = ../.. -MMSOURCE17 = ../../../mmsource-1.7 - -##################################### -### EDIT BELOW FOR OTHER PROJECTS ### -##################################### - -PROJECT = spshell - -OBJECTS = dll_exports.cpp \ - environment.cpp \ - x86/jit_x86.cpp \ - sp_vm_basecontext.cpp \ - sp_vm_engine.cpp \ - scripted-invoker.cpp \ - engine2.cpp \ - plugin-runtime.cpp \ - compiled-function.cpp \ - opcodes.cpp \ - watchdog_timer.cpp \ - interpreter.cpp \ - md5/md5.cpp \ - zlib/adler32.c \ - zlib/compress.c \ - zlib/crc32.c \ - zlib/deflate.c \ - zlib/gzio.c \ - zlib/infback.c \ - zlib/inffast.c \ - zlib/inflate.c \ - zlib/inftrees.c \ - zlib/trees.c \ - zlib/uncompr.c \ - zlib/zutil.c \ - -OBJECTS += ../../knight/shared/KeCodeAllocator.cpp -OBJECTS += ../../public/jit/x86/assembler-x86.cpp - -############################################## -### CONFIGURE ANY OTHER FLAGS/OPTIONS HERE ### -############################################## - -C_OPT_FLAGS = -DNDEBUG -O3 -funroll-loops -pipe -fno-strict-aliasing -C_DEBUG_FLAGS = -D_DEBUG -DDEBUG -g -ggdb3 -C_GCC4_FLAGS = -fvisibility=hidden -CXX_GCC4_FLAGS = -fvisibility-inlines-hidden -CXX = c++ -CC = cc - -LINK = -m32 -lm -lpthread -lrt - -INCLUDE = -I. -I.. -I$(SMSDK)/public -I$(SMSDK)/public/jit -I$(SMSDK)/public/jit/x86 \ - -I$(SMSDK)/public/sourcepawn -I$(MMSOURCE17)/core/sourcehook -I$(SMSDK)/knight/shared -Ix86 \ - -I$(SMSDK)/public/amtl -I$(SMSDK)/sourcepawn/include - -CFLAGS += -D_LINUX -Dstricmp=strcasecmp -D_stricmp=strcasecmp -D_strnicmp=strncasecmp -Dstrnicmp=strncasecmp \ - -D_snprintf=snprintf -D_vsnprintf=vsnprintf -D_alloca=alloca -Dstrcmpi=strcasecmp -Wall -DHAVE_STDINT_H \ - -m32 -Wno-uninitialized -Werror -DSPSHELL -ggdb3 -Wno-unused -CXXFLAGS += -Wno-non-virtual-dtor -fno-exceptions -fno-rtti -Wno-delete-non-virtual-dtor -std=c++11 - -################################################ -### DO NOT EDIT BELOW HERE FOR MOST PROJECTS ### -################################################ - -ifeq "$(DEBUG)" "true" - BIN_DIR = Debug.shell - CFLAGS += $(C_DEBUG_FLAGS) -else - BIN_DIR = Release.shell - CFLAGS += $(C_OPT_FLAGS) -endif - -GCC_VERSION := $(shell $(CXX) -dumpversion >&1 | cut -b1) -ifeq "$(GCC_VERSION)" "4" - CFLAGS += $(C_GCC4_FLAGS) - CXXFLAGS += $(CXX_GCC4_FLAGS) -endif - -OBJ_LINUX := $(OBJECTS:../../knight/shared/%.cpp=$(BIN_DIR)/knight/%.o) -OBJ_LINUX := $(OBJ_LINUX:../../public/jit/x86/%.cpp=$(BIN_DIR)/%.o) -OBJ_LINUX := $(OBJ_LINUX:%.cpp=$(BIN_DIR)/%.o) -OBJ_LINUX := $(OBJ_LINUX:%.c=$(BIN_DIR)/%.o) - -default: all - -$(BIN_DIR)/%.o: %.c - $(CC) $(INCLUDE) $(CFLAGS) -o $@ -c $< - -$(BIN_DIR)/%.o: %.cpp - $(CXX) $(INCLUDE) $(CFLAGS) $(CXXFLAGS) -o $@ -c $< - -$(BIN_DIR)/knight/%.o: ../../knight/shared/%.cpp - $(CXX) $(INCLUDE) $(CFLAGS) $(CXXFLAGS) -o $@ -c $< - -$(BIN_DIR)/assembler-x86.o: ../../public/jit/x86/assembler-x86.cpp - $(CXX) $(INCLUDE) $(CFLAGS) $(CXXFLAGS) -o $@ -c $< - -all: - mkdir -p $(BIN_DIR)/x86 - mkdir -p $(BIN_DIR)/md5 - mkdir -p $(BIN_DIR)/zlib - mkdir -p $(BIN_DIR)/knight - $(MAKE) -f Makefile.shell jit - -jit: $(OBJ_LINUX) - $(CXX) $(INCLUDE) $(OBJ_LINUX) $(LINK) -o $(BIN_DIR)/$(PROJECT) - -debug: - $(MAKE) -f Makefile.shell all DEBUG=true - -clean: - rm -f $(BIN_DIR)/x86/*.o -# rm -rf $(BIN_DIR)/zlib/*.o -# rm -rf $(BIN_DIR)/knight/*.o - rm -f $(BIN_DIR)/*.o - rm -f $(BIN_DIR)/$(PROJECT) - diff --git a/sourcepawn/vm/api.cpp b/sourcepawn/vm/api.cpp deleted file mode 100644 index 849642ec..00000000 --- a/sourcepawn/vm/api.cpp +++ /dev/null @@ -1,405 +0,0 @@ -// vim: set sts=2 ts=8 sw=2 tw=99 et: -// -// Copyright (C) 2006-2015 AlliedModders LLC -// -// This file is part of SourcePawn. SourcePawn is free software: you can -// redistribute it and/or modify it under the terms of the GNU General Public -// License as published by the Free Software Foundation, either version 3 of -// the License, or (at your option) any later version. -// -// You should have received a copy of the GNU General Public License along with -// SourcePawn. If not, see http://www.gnu.org/licenses/. -// -#include -#include -#include -#include -#include "x86/jit_x86.h" -#include "environment.h" -#include "api.h" -#include -#if defined __GNUC__ -#include -#endif - -#if defined WIN32 - #define WIN32_LEAN_AND_MEAN - #include -#elif defined __GNUC__ - #include -#endif - -#if defined __linux__ -#include -#endif - -#include -#include "code-stubs.h" -#include "smx-v1-image.h" - -using namespace sp; -using namespace SourcePawn; - -// ////// // -// API v1 -// ////// // - -SourcePawnEngine::SourcePawnEngine() -{ -} - -const char * -SourcePawnEngine::GetErrorString(int error) -{ - return Environment::get()->GetErrorString(error); -} - -void * -SourcePawnEngine::ExecAlloc(size_t size) -{ -#if defined WIN32 - return VirtualAlloc(NULL, size, MEM_COMMIT, PAGE_EXECUTE_READWRITE); -#elif defined __GNUC__ -# if defined __APPLE__ - void *base = valloc(size); -# else - void *base = memalign(sysconf(_SC_PAGESIZE), size); -# endif - if (mprotect(base, size, PROT_READ|PROT_WRITE|PROT_EXEC) != 0) { - free(base); - return NULL; - } - return base; -#endif -} - -void * -SourcePawnEngine::AllocatePageMemory(size_t size) -{ - return Environment::get()->AllocateCode(size); -} - -void -SourcePawnEngine::SetReadExecute(void *ptr) -{ - /* already re */ -} - -void -SourcePawnEngine::SetReadWrite(void *ptr) -{ - /* already rw */ -} - -void -SourcePawnEngine::FreePageMemory(void *ptr) -{ - Environment::get()->FreeCode(ptr); -} - -void -SourcePawnEngine::ExecFree(void *address) -{ -#if defined WIN32 - VirtualFree(address, 0, MEM_RELEASE); -#elif defined __GNUC__ - free(address); -#endif -} - -void -SourcePawnEngine::SetReadWriteExecute(void *ptr) -{ - //:TODO: g_ExeMemory.SetRWE(ptr); - SetReadExecute(ptr); -} - -void * -SourcePawnEngine::BaseAlloc(size_t size) -{ - return malloc(size); -} - -void -SourcePawnEngine::BaseFree(void *memory) -{ - free(memory); -} - -sp_plugin_t * -SourcePawnEngine::LoadFromFilePointer(FILE *fp, int *err) -{ - if (err != NULL) - *err = SP_ERROR_ABORTED; - - return NULL; -} - -sp_plugin_t * -SourcePawnEngine::LoadFromMemory(void *base, sp_plugin_t *plugin, int *err) -{ - if (err != NULL) - *err = SP_ERROR_ABORTED; - - return NULL; -} - -int -SourcePawnEngine::FreeFromMemory(sp_plugin_t *plugin) -{ - return SP_ERROR_ABORTED; -} - -IDebugListener * -SourcePawnEngine::SetDebugListener(IDebugListener *pListener) -{ - IDebugListener *old = Environment::get()->debugger(); - Environment::get()->SetDebugger(pListener); - return old; -} - -unsigned int -SourcePawnEngine::GetEngineAPIVersion() -{ - return 4; -} - -unsigned int -SourcePawnEngine::GetContextCallCount() -{ - return 0; -} - -// ////// // -// API v2 -// ////// // - -SourcePawnEngine2::SourcePawnEngine2() -{ -} - -size_t -sp::UTIL_FormatVA(char *buffer, size_t maxlength, const char *fmt, va_list ap) -{ - size_t len = vsnprintf(buffer, maxlength, fmt, ap); - - if (len >= maxlength) { - buffer[maxlength - 1] = '\0'; - return maxlength - 1; - } - return len; -} - -size_t -sp::UTIL_Format(char *buffer, size_t maxlength, const char *fmt, ...) -{ - va_list ap; - - va_start(ap, fmt); - size_t len = UTIL_FormatVA(buffer, maxlength, fmt, ap); - va_end(ap); - - return len; -} - -IPluginRuntime * -SourcePawnEngine2::LoadPlugin(ICompilation *co, const char *file, int *err) -{ - if (co) { - if (err) - *err = SP_ERROR_PARAM; - return nullptr; - } - - IPluginRuntime *rt = LoadBinaryFromFile(file, nullptr, 0); - if (!rt) { - if (err) { - if (FILE *fp = fopen(file, "rb")) { - fclose(fp); - *err = SP_ERROR_FILE_FORMAT; - } else { - *err = SP_ERROR_NOT_FOUND; - } - } - return nullptr; - } - - return rt; -} - -IPluginRuntime * -SourcePawnEngine2::LoadBinaryFromFile(const char *file, char *error, size_t maxlength) -{ - FILE *fp = fopen(file, "rb"); - - if (!fp) { - UTIL_Format(error, maxlength, "file not found"); - return nullptr; - } - - ke::AutoPtr image(new SmxV1Image(fp)); - fclose(fp); - - if (!image->validate()) { - const char *errorMessage = image->errorMessage(); - if (!errorMessage) - errorMessage = "file parse error"; - UTIL_Format(error, maxlength, "%s", errorMessage); - return nullptr; - } - - PluginRuntime *pRuntime = new PluginRuntime(image.take()); - if (!pRuntime->Initialize()) { - delete pRuntime; - - UTIL_Format(error, maxlength, "out of memory"); - return nullptr; - } - - size_t len = strlen(file); - for (size_t i = len - 1; i < len; i--) { - if (file[i] == '/' -# if defined WIN32 - || file[i] == '\\' -# endif - ) - { - pRuntime->SetNames(file, &file[i + 1]); - break; - } - } - - if (!pRuntime->Name()) - pRuntime->SetNames(file, file); - - return pRuntime; -} - -SPVM_NATIVE_FUNC -SourcePawnEngine2::CreateFakeNative(SPVM_FAKENATIVE_FUNC callback, void *pData) -{ - return Environment::get()->stubs()->CreateFakeNativeStub(callback, pData); -} - -void -SourcePawnEngine2::DestroyFakeNative(SPVM_NATIVE_FUNC func) -{ - return Environment::get()->FreeCode((void *)func); -} - -const char * -SourcePawnEngine2::GetEngineName() -{ - return "SourcePawn 1.7, jit-x86"; -} - -const char * -SourcePawnEngine2::GetVersionString() -{ - return SOURCEMOD_VERSION; -} - -IDebugListener * -SourcePawnEngine2::SetDebugListener(IDebugListener *listener) -{ - IDebugListener *old = Environment::get()->debugger(); - Environment::get()->SetDebugger(listener); - return old; -} - -unsigned int -SourcePawnEngine2::GetAPIVersion() -{ - return SOURCEPAWN_ENGINE2_API_VERSION; -} - -ICompilation * -SourcePawnEngine2::StartCompilation() -{ - return nullptr; -} - -const char * -SourcePawnEngine2::GetErrorString(int err) -{ - return Environment::get()->GetErrorString(err); -} - -bool -SourcePawnEngine2::Initialize() -{ - return true; -} - -void -SourcePawnEngine2::Shutdown() -{ -} - -IPluginRuntime * -SourcePawnEngine2::CreateEmptyRuntime(const char *name, uint32_t memory) -{ - int err; - - ke::AutoPtr image(new EmptyImage(memory)); - - PluginRuntime *rt = new PluginRuntime(image.take()); - if (!rt->Initialize()) { - delete rt; - return NULL; - } - - if (!name) - name = ""; - rt->SetNames(name, name); - return rt; -} - -bool -SourcePawnEngine2::InstallWatchdogTimer(size_t timeout_ms) -{ - return Environment::get()->InstallWatchdogTimer(timeout_ms); -} - -bool -SourcePawnEngine2::SetJitEnabled(bool enabled) -{ - Environment::get()->SetJitEnabled(enabled); - return Environment::get()->IsJitEnabled() == enabled; -} - -bool -SourcePawnEngine2::IsJitEnabled() -{ - return Environment::get()->IsJitEnabled(); -} - -void -SourcePawnEngine2::SetProfiler(IProfiler *profiler) -{ - // Deprecated. -} - -void -SourcePawnEngine2::EnableProfiling() -{ - Environment::get()->EnableProfiling(); -} - -void -SourcePawnEngine2::DisableProfiling() -{ - Environment::get()->DisableProfiling(); -} - -void -SourcePawnEngine2::SetProfilingTool(IProfilingTool *tool) -{ - Environment::get()->SetProfiler(tool); -} - -ISourcePawnEnvironment * -SourcePawnEngine2::Environment() -{ - return Environment::get(); -} diff --git a/sourcepawn/vm/api.h b/sourcepawn/vm/api.h deleted file mode 100644 index 5000f9a5..00000000 --- a/sourcepawn/vm/api.h +++ /dev/null @@ -1,79 +0,0 @@ -// vim: set sts=2 ts=8 sw=2 tw=99 et: -// -// Copyright (C) 2006-2015 AlliedModders LLC -// -// This file is part of SourcePawn. SourcePawn is free software: you can -// redistribute it and/or modify it under the terms of the GNU General Public -// License as published by the Free Software Foundation, either version 3 of -// the License, or (at your option) any later version. -// -// You should have received a copy of the GNU General Public License along with -// SourcePawn. If not, see http://www.gnu.org/licenses/. -// -#ifndef _include_sourcepawn_vm_api_h_ -#define _include_sourcepawn_vm_api_h_ - -#include -#include // Replace with am-cxx later. - -namespace sp { - -using namespace SourcePawn; - -class SourcePawnEngine : public ISourcePawnEngine -{ - public: - SourcePawnEngine(); - - sp_plugin_t *LoadFromFilePointer(FILE *fp, int *err) KE_OVERRIDE; - sp_plugin_t *LoadFromMemory(void *base, sp_plugin_t *plugin, int *err) KE_OVERRIDE; - int FreeFromMemory(sp_plugin_t *plugin) KE_OVERRIDE; - void *BaseAlloc(size_t size) KE_OVERRIDE; - void BaseFree(void *memory) KE_OVERRIDE; - void *ExecAlloc(size_t size) KE_OVERRIDE; - void ExecFree(void *address) KE_OVERRIDE; - IDebugListener *SetDebugListener(IDebugListener *pListener) KE_OVERRIDE; - unsigned int GetContextCallCount() KE_OVERRIDE; - unsigned int GetEngineAPIVersion() KE_OVERRIDE; - void *AllocatePageMemory(size_t size) KE_OVERRIDE; - void SetReadWrite(void *ptr) KE_OVERRIDE; - void SetReadExecute(void *ptr) KE_OVERRIDE; - void FreePageMemory(void *ptr) KE_OVERRIDE; - void SetReadWriteExecute(void *ptr); - const char *GetErrorString(int err); -}; - -class SourcePawnEngine2 : public ISourcePawnEngine2 -{ - public: - SourcePawnEngine2(); - - unsigned int GetAPIVersion() KE_OVERRIDE; - const char *GetEngineName() KE_OVERRIDE; - const char *GetVersionString() KE_OVERRIDE; - IPluginRuntime *LoadPlugin(ICompilation *co, const char *file, int *err) KE_OVERRIDE; - SPVM_NATIVE_FUNC CreateFakeNative(SPVM_FAKENATIVE_FUNC callback, void *pData) KE_OVERRIDE; - void DestroyFakeNative(SPVM_NATIVE_FUNC func) KE_OVERRIDE; - IDebugListener *SetDebugListener(IDebugListener *listener) KE_OVERRIDE; - ICompilation *StartCompilation() KE_OVERRIDE; - const char *GetErrorString(int err) KE_OVERRIDE; - bool Initialize() KE_OVERRIDE; - void Shutdown() KE_OVERRIDE; - IPluginRuntime *CreateEmptyRuntime(const char *name, uint32_t memory) KE_OVERRIDE; - bool InstallWatchdogTimer(size_t timeout_ms) KE_OVERRIDE; - bool SetJitEnabled(bool enabled) KE_OVERRIDE; - bool IsJitEnabled() KE_OVERRIDE; - void SetProfiler(IProfiler *profiler) KE_OVERRIDE; - void EnableProfiling() KE_OVERRIDE; - void DisableProfiling() KE_OVERRIDE; - void SetProfilingTool(IProfilingTool *tool) KE_OVERRIDE; - IPluginRuntime *LoadBinaryFromFile(const char *file, char *error, size_t maxlength) KE_OVERRIDE; - ISourcePawnEnvironment *Environment() KE_OVERRIDE; -}; - -extern size_t UTIL_Format(char *buffer, size_t maxlength, const char *fmt, ...); -extern size_t UTIL_FormatVA(char *buffer, size_t maxlength, const char *fmt, va_list ap); - -} // namespace sp - -#endif // _include_sourcepawn_vm_api_h_ diff --git a/sourcepawn/vm/assembler.h b/sourcepawn/vm/assembler.h deleted file mode 100644 index 8e82e744..00000000 --- a/sourcepawn/vm/assembler.h +++ /dev/null @@ -1,305 +0,0 @@ -/** - * vim: set ts=8 sts=2 sw=2 tw=99 et: - * ============================================================================= - * SourcePawn JIT SDK - * Copyright (C) 2004-2013 AlliedModders LLC. All rights reserved. - * ============================================================================= - * - * This program is free software; you can redistribute it and/or modify it under - * the terms of the GNU General Public License, version 3.0, as published by the - * Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS - * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more - * details. - * - * You should have received a copy of the GNU General Public License along with - * this program. If not, see . - * - * As a special exception, AlliedModders LLC gives you permission to link the - * code of this program (as well as its derivative works) to "Half-Life 2," the - * "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software - * by the Valve Corporation. You must obey the GNU General Public License in - * all respects for all other code used. Additionally, AlliedModders LLC grants - * this exception to all derivative works. AlliedModders LLC defines further - * exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007), - * or . - * - * Version: $Id$ - */ -#ifndef _include_sourcepawn_assembler_h__ -#define _include_sourcepawn_assembler_h__ - -#include -#include -#include -#include -#include - -class Assembler -{ - public: - static const size_t kMinBufferSize = 4096; - static const size_t kMaxInstructionSize = 32; - static const size_t kMaxBufferSize = INT_MAX / 2; - - public: - Assembler() { - buffer_ = (uint8_t *)malloc(kMinBufferSize); - pos_ = buffer_; - end_ = buffer_ + kMinBufferSize; - outOfMemory_ = !buffer_; - } - ~Assembler() { - free(buffer_); - } - - bool outOfMemory() const { - return outOfMemory_; - } - - // Amount needed to allocate for executable code. - size_t length() const { - return pos_ - buffer_; - } - - // Current offset into the code stream. - uint32_t pc() const { - return uint32_t(pos_ - buffer_); - } - - protected: - void writeByte(uint8_t byte) { - write(byte); - } - void writeInt32(int32_t word) { - write(word); - } - void writeUint32(uint32_t word) { - write(word); - } - void writePointer(void *ptr) { - write(ptr); - } - - template - void write(const T &t) { - assertCanWrite(sizeof(T)); - *reinterpret_cast(pos_) = t; - pos_ += sizeof(T); - } - - // Normally this does not need to be checked, but it must be called before - // emitting any instruction. - bool ensureSpace() { - if (pos_ + kMaxInstructionSize <= end_) - return true; - - if (outOfMemory()) - return false; - - size_t oldlength = size_t(end_ - buffer_); - - if (oldlength * 2 > kMaxBufferSize) { - // See comment when if realloc() fails. - pos_ = buffer_; - outOfMemory_ = true; - return false; - } - - size_t oldpos = size_t(pos_ - buffer_); - uint8_t *newbuf = (uint8_t *)realloc(buffer_, oldlength * 2); - if (!newbuf) { - // Writes will be safe, though we'll corrupt the instruction stream, so - // actually using the buffer will be invalid and compilation should be - // aborted when possible. - pos_ = buffer_; - outOfMemory_ = true; - return false; - } - buffer_ = newbuf; - end_ = newbuf + oldlength * 2; - pos_ = buffer_ + oldpos; - return true; - } - - // Position will never be negative, but it's nice to have signed results - // for relative address calculation. - int32_t position() const { - return int32_t(pos_ - buffer_); - } - - protected: - void assertCanWrite(size_t bytes) { - assert(pos_ + bytes <= end_); - } - uint8_t *buffer() const { - return buffer_; - } - - private: - uint8_t *buffer_; - uint8_t *end_; - - protected: - uint8_t *pos_; - bool outOfMemory_; -}; - -class ExternalAddress -{ - public: - explicit ExternalAddress(void *p) - : p_(p) - { - } - - void *address() const { - return p_; - } - uintptr_t value() const { - return uintptr_t(p_); - } - - private: - void *p_; -}; - -// A label is a lightweight object to assist in managing relative jumps. It -// exists in three states: -// * Unbound, Unused: The label has no incoming jumps, and its position has -// not yet been fixed in the instruction stream. -// * Unbound, Used: The label has not yet been fixed at a position in the -// instruction stream, but it has incoming jumps. -// * Bound: The label has been fixed at a position in the instruction stream. -// -// When a label is unbound and used, the offset stored in the Label is a linked -// list threaded through each individual jump. When the label is bound, each -// jump instruction in this list is immediately patched with the correctly -// computed relative distance to the label. -// -// We keep sizeof(Label) == 4 to make it embeddable within code streams if -// need be (for example, SourcePawn mirrors the source code to maintain jump -// maps). -class Label -{ - // If set on status_, the label is bound. - static const int32_t kBound = (1 << 0); - - public: - Label() - : status_(0) - { - } - ~Label() - { - assert(!used() || bound()); - } - - static inline bool More(uint32_t status) { - return status != 0; - } - static inline uint32_t ToOffset(uint32_t status) { - return status >> 1; - } - - bool used() const { - return bound() || !!(status_ >> 1); - } - bool bound() const { - return !!(status_ & kBound); - } - uint32_t offset() const { - assert(bound()); - return ToOffset(status_); - } - uint32_t status() const { - assert(!bound()); - return status_; - } - uint32_t addPending(uint32_t pc) { - assert(pc <= INT_MAX / 2); - uint32_t prev = status_; - status_ = pc << 1; - return prev; - } - void bind(uint32_t offset) { - assert(!bound()); - status_ = (offset << 1) | kBound; - assert(this->offset() == offset); - } - - protected: - // Note that 0 as an invalid offset is okay, because the offset we save for - // pending jumps are after the jump opcode itself, and therefore 0 is never - // valid, since there are no 0-byte jumps. - uint32_t status_; -}; - -// Label that suppresses its assert, for non-stack use. -class SilentLabel : public Label -{ - public: - SilentLabel() - {} - ~SilentLabel() { - status_ = 0; - } -}; - -// A DataLabel is a special form of Label intended for absolute addresses that -// are within the code buffer, and thus aren't known yet, and will be -// automatically fixed up when calling emitToExecutableMemory(). -// -// Unlike normal Labels, these do not store a list of incoming uses. -class DataLabel -{ - // If set on status_, the label is bound. - static const int32_t kBound = (1 << 0); - - public: - DataLabel() - : status_(0) - { - } - ~DataLabel() - { - assert(!used() || bound()); - } - - static inline uint32_t ToOffset(uint32_t status) { - return status >> 1; - } - - bool used() const { - return bound() || !!(status_ >> 1); - } - bool bound() const { - return !!(status_ & kBound); - } - uint32_t offset() const { - assert(bound()); - return ToOffset(status_); - } - uint32_t status() const { - assert(!bound()); - return status_; - } - void use(uint32_t pc) { - assert(!used()); - status_ = (pc << 1); - assert(ToOffset(status_) == pc); - } - void bind(uint32_t offset) { - assert(!bound()); - status_ = (offset << 1) | kBound; - assert(this->offset() == offset); - } - - private: - uint32_t status_; -}; - -#endif // _include_sourcepawn_assembler_h__ - diff --git a/sourcepawn/vm/code-allocator.cpp b/sourcepawn/vm/code-allocator.cpp deleted file mode 100644 index b9773e0a..00000000 --- a/sourcepawn/vm/code-allocator.cpp +++ /dev/null @@ -1,419 +0,0 @@ -#include -#include -#include - -#if defined(WIN32) -#include -#else -#include -#include -#include -#endif - -#include "code-allocator.h" - -#define ALIGNMENT 16 - -using namespace Knight; - -struct KeFreedCode; - -/** - * Defines a region of memory that is made of pages. - */ -struct KeCodeRegion -{ - KeCodeRegion *next; - unsigned char *block_start; - unsigned char *block_pos; - KeFreedCode *free_list; - size_t total_size; - size_t end_free; - size_t total_free; -}; - -/** - * Defines freed code. We keep the size here because - * when we touch the linked list we don't want to dirty pages. - */ -struct KeFreedCode -{ - KeCodeRegion *region; - unsigned char *block_start; - size_t size; - KeFreedCode *next; -}; - -struct KeSecret -{ - KeCodeRegion *region; - size_t size; -}; - -class Knight::KeCodeCache -{ -public: - /** - * First region that is live for use. - */ - KeCodeRegion *first_live; - - /** - * First region that is full but has free entries. - */ - KeCodeRegion *first_partial; - - /** - * First region that is full. - */ - KeCodeRegion *first_full; - - /** - * Page granularity and size. - */ - unsigned int page_size; - unsigned int page_granularity; - - /** - * This isn't actually for code, this is the node cache. - */ - KeCodeRegion *node_cache; - KeFreedCode *free_node_list; -}; - -KeCodeCache *Knight::KE_CreateCodeCache() -{ - KeCodeCache *cache; - - cache = new KeCodeCache; - - memset(cache, 0, sizeof(KeCodeCache)); - -#if defined(WIN32) - SYSTEM_INFO info; - - GetSystemInfo(&info); - cache->page_size = info.dwPageSize; - cache->page_granularity = info.dwAllocationGranularity; -#else - cache->page_size = cache->page_granularity = sysconf(_SC_PAGESIZE); -#endif - - return cache; -} - -inline size_t MinAllocSize() -{ - size_t size; - - size = sizeof(KeSecret); - size += ALIGNMENT; - size -= size % ALIGNMENT; - - return size; -} - -inline size_t ke_GetAllocSize(size_t size) -{ - size += sizeof(KeSecret); - size += ALIGNMENT; - size -= size % ALIGNMENT; - - return size; -} - -void *ke_AllocInRegion(KeCodeCache *cache, - KeCodeRegion **prev, - KeCodeRegion *region, - unsigned char *ptr, - size_t alloc_size, - bool is_live) -{ - KeSecret *secret; - - /* Squirrel some info in the alloc. */ - secret = (KeSecret *)ptr; - secret->region = region; - secret->size = alloc_size; - ptr += sizeof(KeSecret); - - region->total_free -= alloc_size; - - /* Check if we can't use the fast-path anymore. */ - if ((is_live && region->end_free < MinAllocSize()) - || (!is_live && region->total_free < MinAllocSize())) - { - KeCodeRegion **start; - - *prev = region->next; - - /* Select the appropriate arena. */ - if (is_live) - { - if (region->total_free < MinAllocSize()) - { - start = &cache->first_full; - } - else - { - start = &cache->first_partial; - } - } - else - { - start = &cache->first_full; - } - - region->next = *start; - *start = region; - } - - return ptr; -} - -void *ke_AllocFromLive(KeCodeCache *cache, size_t size) -{ - void *ptr; - size_t alloc_size; - KeCodeRegion *region, **prev; - - region = cache->first_live; - prev = &cache->first_live; - alloc_size = ke_GetAllocSize(size); - - while (region != NULL) - { - if (region->end_free >= alloc_size) - { - /* Yay! We can do a simple alloc here. */ - ptr = ke_AllocInRegion(cache, prev, region, region->block_pos, alloc_size, true); - - /* Update our counters. */ - region->block_pos += alloc_size; - region->end_free -= alloc_size; - - return ptr; - } - prev = ®ion->next; - region = region->next; - } - - return NULL; -} - -void *ke_AllocFromPartial(KeCodeCache *cache, size_t size) -{ - void *ptr; - size_t alloc_size; - KeCodeRegion *region, **prev; - - region = cache->first_partial; - prev = &cache->first_partial; - alloc_size = ke_GetAllocSize(size); - - while (region != NULL) - { - if (region->total_free >= alloc_size) - { - KeFreedCode *node, **last; - - assert(region->free_list != NULL); - - last = ®ion->free_list; - node = region->free_list; - while (node != NULL) - { - if (node->size >= alloc_size) - { - /* Use this node */ - ptr = ke_AllocInRegion(cache, prev, region, node->block_start, alloc_size, false); - - region->total_free -= node->size; - *last = node->next; - - /* Make sure bookkeepping is correct. */ - assert((region->free_list == NULL && region->total_free == 0) - || (region->free_list != NULL && region->total_free != 0)); - - /* Link us back into the free node list. */ - node->next = cache->free_node_list; - cache->free_node_list = node->next; - - return ptr; - } - last = &node->next; - node = node->next; - } - } - prev = ®ion->next; - region = region->next; - } - - return NULL; -} - -KeCodeRegion *ke_AddRegionForSize(KeCodeCache *cache, size_t size) -{ - KeCodeRegion *region; - - region = new KeCodeRegion; - - size = ke_GetAllocSize(size); - size += cache->page_granularity * 2; - size -= size % cache->page_granularity; - -#if defined(WIN32) - region->block_start = (unsigned char *)VirtualAlloc(NULL, size, MEM_COMMIT|MEM_RESERVE, PAGE_EXECUTE_READWRITE); -#else - region->block_start = (unsigned char *)mmap(NULL, size, PROT_READ|PROT_WRITE|PROT_EXEC, MAP_PRIVATE|MAP_ANON, -1, 0); - region->block_start = (region->block_start == MAP_FAILED) ? NULL : region->block_start; -#endif - - if (region->block_start == NULL) - { - delete region; - return NULL; - } - - region->block_pos = region->block_start; - region->end_free = region->total_free = region->total_size = size; - region->next = cache->first_live; - cache->first_live = region; - region->free_list = NULL; - - return region; -} - -void *Knight::KE_AllocCode(KeCodeCache *cache, size_t size) -{ - void *ptr; - - /* Check live easy-adds */ - if (cache->first_live != NULL) - { - if ((ptr = ke_AllocFromLive(cache, size)) != NULL) - { - return ptr; - } - } - - /* Try looking in the free lists */ - if (cache->first_partial != NULL) - { - if ((ptr = ke_AllocFromPartial(cache, size)) != NULL) - { - return ptr; - } - } - - /* Create a new region */ - if (ke_AddRegionForSize(cache, size) == NULL) - { - return NULL; - } - - return ke_AllocFromLive(cache, size); -} - -KeFreedCode *ke_GetFreeNode(KeCodeCache *cache) -{ - KeFreedCode *ret; - - if (cache->free_node_list != NULL) - { - ret = cache->free_node_list; - cache->free_node_list = ret->next; - - return ret; - } - - /* See if the current free node region has space. */ - if (cache->node_cache != NULL - && cache->node_cache->end_free >= sizeof(KeFreedCode)) - { - ret = (KeFreedCode *)cache->node_cache->block_pos; - cache->node_cache->block_pos += sizeof(KeFreedCode); - cache->node_cache->total_free -= sizeof(KeFreedCode); - cache->node_cache->end_free -= sizeof(KeFreedCode); - - return ret; - } - - /* Otherwise, we need to alloc a new region. */ - KeCodeRegion *region = new KeCodeRegion; - - region->block_start = new unsigned char[cache->page_size / sizeof(KeFreedCode)]; - region->block_pos = region->block_start + sizeof(KeFreedCode); - region->total_size = cache->page_size / sizeof(KeFreedCode); - region->total_free = region->end_free = (region->total_size - sizeof(KeFreedCode)); - region->free_list = NULL; - region->next = cache->node_cache; - cache->node_cache = region; - - return (KeFreedCode *)region->block_start; -} - -void Knight::KE_FreeCode(KeCodeCache *cache, void *code) -{ - KeSecret *secret; - KeFreedCode *node; - unsigned char *ptr; - KeCodeRegion *region; - - ptr = (unsigned char *)code; - secret = (KeSecret *)(ptr - sizeof(KeSecret)); - region = secret->region; - node = ke_GetFreeNode(cache); - node->block_start = (unsigned char *)code; - node->next = region->free_list; - region->free_list = node; - node->region = region; - node->size = secret->size; -} - -KeCodeRegion *ke_DestroyRegion(KeCodeRegion *region) -{ - KeCodeRegion *next; - - next = region->next; - -#if defined(WIN32) - VirtualFree(region->block_start, 0, MEM_RELEASE); -#else - munmap(region->block_start, region->total_size); -#endif - - delete region; - - return next; -} - -void ke_DestroyRegionChain(KeCodeRegion *first) -{ - while (first != NULL) - { - first = ke_DestroyRegion(first); - } -} - -void Knight::KE_DestroyCodeCache(KeCodeCache *cache) -{ - /* Destroy every region and call it a day. */ - ke_DestroyRegionChain(cache->first_full); - ke_DestroyRegionChain(cache->first_live); - ke_DestroyRegionChain(cache->first_partial); - - /* We use normal malloc for node cache regions */ - KeCodeRegion *region, *next; - - region = cache->node_cache; - while (region != NULL) - { - next = region->next; - delete [] region->block_start; - delete region; - region = next; - } - - delete cache; -} diff --git a/sourcepawn/vm/code-allocator.h b/sourcepawn/vm/code-allocator.h deleted file mode 100644 index b07544dc..00000000 --- a/sourcepawn/vm/code-allocator.h +++ /dev/null @@ -1,47 +0,0 @@ -#ifndef _INCLUDE_KNIGHT_KE_CODE_ALLOCATOR_H_ -#define _INCLUDE_KNIGHT_KE_CODE_ALLOCATOR_H_ - -#include -#include - -namespace Knight -{ - class KeCodeCache; - - /** - * @brief Creates a new code cache/allocator. - * - * @return New code cache allocator. - */ - extern KeCodeCache *KE_CreateCodeCache(); - - /** - * @brief Destroys a code cache allocator. - * - * @param cache Code cache object. - */ - extern void KE_DestroyCodeCache(KeCodeCache *cache); - - /** - * @brief Allocates code memory that is readable, writable, - * and executable. - * - * The address returned wlil be aligned, minimally, on a 16-byte - * boundary. - * - * @param cache Code cache object. - * @param size Amount of memory needed. - * @return Address pointing to the memory. - */ - extern void *KE_AllocCode(KeCodeCache *cache, size_t size); - - /** - * @brief Frees code memory. - * - * @param cache Code cache object. - * @param code Address of code memory. - */ - extern void KE_FreeCode(KeCodeCache *cache, void *code); -} - -#endif //_INCLUDE_KNIGHT_KE_CODE_ALLOCATOR_H_ diff --git a/sourcepawn/vm/code-stubs.cpp b/sourcepawn/vm/code-stubs.cpp deleted file mode 100644 index 2906f586..00000000 --- a/sourcepawn/vm/code-stubs.cpp +++ /dev/null @@ -1,40 +0,0 @@ -// vim: set sts=2 ts=8 sw=2 tw=99 et: -// -// Copyright (C) 2006-2015 AlliedModders LLC -// -// This file is part of SourcePawn. SourcePawn is free software: you can -// redistribute it and/or modify it under the terms of the GNU General Public -// License as published by the Free Software Foundation, either version 3 of -// the License, or (at your option) any later version. -// -// You should have received a copy of the GNU General Public License along with -// SourcePawn. If not, see http://www.gnu.org/licenses/. -// -#include "code-stubs.h" -#include "environment.h" - -using namespace sp; - -CodeStubs::CodeStubs(Environment *env) - : env_(env), - invoke_stub_(nullptr), - return_stub_(nullptr) -{ -} - -bool -CodeStubs::Initialize() -{ - if (!InitializeFeatureDetection()) - return false; - if (!CompileInvokeStub()) - return false; - return true; -} - -void -CodeStubs::Shutdown() -{ - if (invoke_stub_) - env_->FreeCode(invoke_stub_); -} diff --git a/sourcepawn/vm/code-stubs.h b/sourcepawn/vm/code-stubs.h deleted file mode 100644 index 82cbcaae..00000000 --- a/sourcepawn/vm/code-stubs.h +++ /dev/null @@ -1,56 +0,0 @@ -// vim: set sts=2 ts=8 sw=2 tw=99 et: -// -// Copyright (C) 2006-2015 AlliedModders LLC -// -// This file is part of SourcePawn. SourcePawn is free software: you can -// redistribute it and/or modify it under the terms of the GNU General Public -// License as published by the Free Software Foundation, either version 3 of -// the License, or (at your option) any later version. -// -// You should have received a copy of the GNU General Public License along with -// SourcePawn. If not, see http://www.gnu.org/licenses/. -// -#ifndef _include_sourcepawn_vm_code_stubs_h_ -#define _include_sourcepawn_vm_code_stubs_h_ - -#include -#include - -namespace sp { - -class PluginContext; -class Environment; - -typedef int (*InvokeStubFn)(PluginContext *cx, void *code, cell_t *rval); - -class CodeStubs -{ - public: - CodeStubs(Environment *env); - - public: - bool Initialize(); - void Shutdown(); - - SPVM_NATIVE_FUNC CreateFakeNativeStub(SPVM_FAKENATIVE_FUNC callback, void *userData); - - InvokeStubFn InvokeStub() const { - return (InvokeStubFn)invoke_stub_; - } - void *ReturnStub() const { - return return_stub_; - } - - private: - bool InitializeFeatureDetection(); - bool CompileInvokeStub(); - - private: - Environment *env_; - void *invoke_stub_; - void *return_stub_; // Owned by invoke_stub_. -}; - -} - -#endif // _include_sourcepawn_vm_code_stubs_h_ diff --git a/sourcepawn/vm/compiled-function.cpp b/sourcepawn/vm/compiled-function.cpp deleted file mode 100644 index b720166a..00000000 --- a/sourcepawn/vm/compiled-function.cpp +++ /dev/null @@ -1,71 +0,0 @@ -// vim: set sts=2 ts=8 sw=2 tw=99 et: -// -// Copyright (C) 2006-2015 AlliedModders LLC -// -// This file is part of SourcePawn. SourcePawn is free software: you can -// redistribute it and/or modify it under the terms of the GNU General Public -// License as published by the Free Software Foundation, either version 3 of -// the License, or (at your option) any later version. -// -// You should have received a copy of the GNU General Public License along with -// SourcePawn. If not, see http://www.gnu.org/licenses/. -// -#include "compiled-function.h" -#include "x86/jit_x86.h" -#include "environment.h" - -using namespace sp; - -CompiledFunction::CompiledFunction(void *entry_addr, size_t code_length, - cell_t pcode_offs, - FixedArray *edges, - FixedArray *cipmap) - : entry_(entry_addr), - code_length_(code_length), - code_offset_(pcode_offs), - edges_(edges), - cip_map_(cipmap) -{ -} - -CompiledFunction::~CompiledFunction() -{ - Environment::get()->FreeCode(entry_); -} - -static int cip_map_entry_cmp(const void *a1, const void *aEntry) -{ - uint32_t pcoffs = (uint32_t)a1; - const CipMapEntry *entry = reinterpret_cast(aEntry); - if (pcoffs < entry->pcoffs) - return -1; - if (pcoffs == entry->pcoffs) - return 0; - return pcoffs > entry->pcoffs; -} - -ucell_t -CompiledFunction::FindCipByPc(void *pc) -{ - if (uintptr_t(pc) < uintptr_t(entry_)) - return kInvalidCip; - - uint32_t pcoffs = intptr_t(pc) - intptr_t(entry_); - if (pcoffs > code_length_) - return kInvalidCip; - - void *ptr = bsearch( - (void *)pcoffs, - cip_map_->buffer(), - cip_map_->length(), - sizeof(CipMapEntry), - cip_map_entry_cmp); - assert(ptr); - - if (!ptr) { - // Shouldn't happen, but fail gracefully. - return kInvalidCip; - } - - return code_offset_ + reinterpret_cast(ptr)->cipoffs; -} diff --git a/sourcepawn/vm/compiled-function.h b/sourcepawn/vm/compiled-function.h deleted file mode 100644 index a4ac782f..00000000 --- a/sourcepawn/vm/compiled-function.h +++ /dev/null @@ -1,79 +0,0 @@ -// vim: set sts=2 ts=8 sw=2 tw=99 et: -// -// Copyright (C) 2006-2015 AlliedModders LLC -// -// This file is part of SourcePawn. SourcePawn is free software: you can -// redistribute it and/or modify it under the terms of the GNU General Public -// License as published by the Free Software Foundation, either version 3 of -// the License, or (at your option) any later version. -// -// You should have received a copy of the GNU General Public License along with -// SourcePawn. If not, see http://www.gnu.org/licenses/. -// -#ifndef _INCLUDE_SOURCEPAWN_JIT2_FUNCTION_H_ -#define _INCLUDE_SOURCEPAWN_JIT2_FUNCTION_H_ - -#include -#include -#include - -namespace sp { - -using namespace ke; - -struct LoopEdge -{ - // Offset to the patchable jump instruction, such that (base + offset - 4) - // yields a patchable location. - uint32_t offset; - // The displacement to either the timeout routine or the original - // displacement, depending on the timeout state. - int32_t disp32; -}; - -struct CipMapEntry { - // Offset from the first cip of the function. - uint32_t cipoffs; - // Offset from the first pc of the function. - uint32_t pcoffs; -}; - -static const ucell_t kInvalidCip = 0xffffffff; - -class CompiledFunction -{ - public: - CompiledFunction(void *entry_addr, - size_t code_length, - cell_t pcode_offs, - FixedArray *edges, - FixedArray *cip_map); - ~CompiledFunction(); - - public: - void *GetEntryAddress() const { - return entry_; - } - cell_t GetCodeOffset() const { - return code_offset_; - } - uint32_t NumLoopEdges() const { - return edges_->length(); - } - LoopEdge &GetLoopEdge(size_t i) { - return edges_->at(i); - } - - ucell_t FindCipByPc(void *pc); - - private: - void *entry_; - size_t code_length_; - cell_t code_offset_; - AutoPtr> edges_; - AutoPtr> cip_map_; -}; - -} - -#endif //_INCLUDE_SOURCEPAWN_JIT2_FUNCTION_H_ diff --git a/sourcepawn/vm/dll_exports.cpp b/sourcepawn/vm/dll_exports.cpp deleted file mode 100644 index 21362351..00000000 --- a/sourcepawn/vm/dll_exports.cpp +++ /dev/null @@ -1,282 +0,0 @@ -/** - * vim: set ts=4 sts=4 sw=4 tw=99 noet: - * ============================================================================= - * SourceMod - * Copyright (C) 2004-2008 AlliedModders LLC. All rights reserved. - * ============================================================================= - * - * This program is free software; you can redistribute it and/or modify it under - * the terms of the GNU General Public License, version 3.0, as published by the - * Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS - * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more - * details. - * - * You should have received a copy of the GNU General Public License along with - * this program. If not, see . - * - * As a special exception, AlliedModders LLC gives you permission to link the - * code of this program (as well as its derivative works) to "Half-Life 2," the - * "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software - * by the Valve Corporation. You must obey the GNU General Public License in - * all respects for all other code used. Additionally, AlliedModders LLC grants - * this exception to all derivative works. AlliedModders LLC defines further - * exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007), - * or . - * - * Version: $Id$ - */ - -#include -#include -#include -#include // Replace with am-cxx later. -#include "dll_exports.h" -#include "environment.h" -#include "stack-frames.h" - -using namespace ke; -using namespace sp; -using namespace SourcePawn; - -class SourcePawnFactory : public ISourcePawnFactory -{ -public: - int ApiVersion() KE_OVERRIDE { - return SOURCEPAWN_API_VERSION; - } - ISourcePawnEnvironment *NewEnvironment() KE_OVERRIDE { - return Environment::New(); - } - ISourcePawnEnvironment *CurrentEnvironment() KE_OVERRIDE { - return Environment::get(); - } -} sFactory; - -#ifdef SPSHELL -Environment *sEnv; - -static void -DumpStack(IFrameIterator &iter) -{ - int index = 0; - for (; !iter.Done(); iter.Next(), index++) { - const char *name = iter.FunctionName(); - if (!name) { - fprintf(stdout, " [%d] \n", index); - continue; - } - - if (iter.IsScriptedFrame()) { - const char *file = iter.FilePath(); - if (!file) - file = ""; - fprintf(stdout, " [%d] %s::%s, line %d\n", index, file, name, iter.LineNumber()); - } else { - fprintf(stdout, " [%d] %s()\n", index, name); - } - } -} - -class ShellDebugListener : public IDebugListener -{ -public: - void ReportError(const IErrorReport &report, IFrameIterator &iter) KE_OVERRIDE { - fprintf(stdout, "Exception thrown: %s\n", report.Message()); - DumpStack(iter); - } - - void OnDebugSpew(const char *msg, ...) { -#if !defined(NDEBUG) && defined(DEBUG) - va_list ap; - va_start(ap, msg); - vfprintf(stderr, msg, ap); - va_end(ap); -#endif - } -}; - -static cell_t Print(IPluginContext *cx, const cell_t *params) -{ - char *p; - cx->LocalToString(params[1], &p); - - return printf("%s", p); -} - -static cell_t PrintNum(IPluginContext *cx, const cell_t *params) -{ - return printf("%d\n", params[1]); -} - -static cell_t PrintNums(IPluginContext *cx, const cell_t *params) -{ - for (size_t i = 1; i <= size_t(params[0]); i++) { - int err; - cell_t *addr; - if ((err = cx->LocalToPhysAddr(params[i], &addr)) != SP_ERROR_NONE) - return cx->ThrowNativeErrorEx(err, "Could not read argument"); - fprintf(stdout, "%d", *addr); - if (i != size_t(params[0])) - fprintf(stdout, ", "); - } - fprintf(stdout, "\n"); - return 1; -} - -static cell_t DoNothing(IPluginContext *cx, const cell_t *params) -{ - return 1; -} - -static void BindNative(IPluginRuntime *rt, const char *name, SPVM_NATIVE_FUNC fn) -{ - int err; - uint32_t index; - if ((err = rt->FindNativeByName(name, &index)) != SP_ERROR_NONE) - return; - - rt->UpdateNativeBinding(index, fn, 0, nullptr); -} - -static cell_t PrintFloat(IPluginContext *cx, const cell_t *params) -{ - return printf("%f\n", sp_ctof(params[1])); -} - -static cell_t DoExecute(IPluginContext *cx, const cell_t *params) -{ - int32_t ok = 0; - for (size_t i = 0; i < size_t(params[2]); i++) { - if (IPluginFunction *fn = cx->GetFunctionById(params[1])) { - if (fn->Execute(nullptr) != SP_ERROR_NONE) - continue; - ok++; - } - } - return ok; -} - -static cell_t DoInvoke(IPluginContext *cx, const cell_t *params) -{ - for (size_t i = 0; i < size_t(params[2]); i++) { - if (IPluginFunction *fn = cx->GetFunctionById(params[1])) { - if (!fn->Invoke()) - return 0; - } - } - return 1; -} - -static cell_t DumpStackTrace(IPluginContext *cx, const cell_t *params) -{ - FrameIterator iter; - DumpStack(iter); - return 0; -} - -static int Execute(const char *file) -{ - char error[255]; - AutoPtr rt(sEnv->APIv2()->LoadBinaryFromFile(file, error, sizeof(error))); - if (!rt) { - fprintf(stderr, "Could not load plugin: %s\n", error); - return 1; - } - - BindNative(rt, "print", Print); - BindNative(rt, "printnum", PrintNum); - BindNative(rt, "printnums", PrintNums); - BindNative(rt, "printfloat", PrintFloat); - BindNative(rt, "donothing", DoNothing); - BindNative(rt, "execute", DoExecute); - BindNative(rt, "invoke", DoInvoke); - BindNative(rt, "dump_stack_trace", DumpStackTrace); - - IPluginFunction *fun = rt->GetFunctionByName("main"); - if (!fun) - return 0; - - IPluginContext *cx = rt->GetDefaultContext(); - - int result; - { - ExceptionHandler eh(cx); - if (!fun->Invoke(&result)) { - fprintf(stderr, "Error executing main: %s\n", eh.Message()); - return 1; - } - } - - return result; -} - -int main(int argc, char **argv) -{ - if (argc != 2) { - fprintf(stderr, "Usage: \n"); - return 1; - } - - if ((sEnv = Environment::New()) == nullptr) { - fprintf(stderr, "Could not initialize ISourcePawnEngine2\n"); - return 1; - } - - if (getenv("DISABLE_JIT")) - sEnv->SetJitEnabled(false); - - ShellDebugListener debug; - sEnv->SetDebugger(&debug); - sEnv->InstallWatchdogTimer(5000); - - int errcode = Execute(argv[1]); - - sEnv->SetDebugger(NULL); - sEnv->Shutdown(); - delete sEnv; - - return errcode; -} - -#else - -#define MIN_API_VERSION 0x0207 - -EXPORTFUNC ISourcePawnFactory * -GetSourcePawnFactory(int apiVersion) -{ - if (apiVersion < MIN_API_VERSION || apiVersion > SOURCEPAWN_API_VERSION) - return nullptr; - return &sFactory; -} -#endif - -#if defined __linux__ || defined __APPLE__ -extern "C" void __cxa_pure_virtual(void) -{ -} - -void *operator new(size_t size) -{ - return malloc(size); -} - -void *operator new[](size_t size) -{ - return malloc(size); -} - -void operator delete(void *ptr) -{ - free(ptr); -} - -void operator delete[](void * ptr) -{ - free(ptr); -} -#endif - diff --git a/sourcepawn/vm/dll_exports.h b/sourcepawn/vm/dll_exports.h deleted file mode 100644 index 2b57676e..00000000 --- a/sourcepawn/vm/dll_exports.h +++ /dev/null @@ -1,47 +0,0 @@ -/** - * vim: set ts=4 : - * ============================================================================= - * SourceMod - * Copyright (C) 2004-2008 AlliedModders LLC. All rights reserved. - * ============================================================================= - * - * This program is free software; you can redistribute it and/or modify it under - * the terms of the GNU General Public License, version 3.0, as published by the - * Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS - * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more - * details. - * - * You should have received a copy of the GNU General Public License along with - * this program. If not, see . - * - * As a special exception, AlliedModders LLC gives you permission to link the - * code of this program (as well as its derivative works) to "Half-Life 2," the - * "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software - * by the Valve Corporation. You must obey the GNU General Public License in - * all respects for all other code used. Additionally, AlliedModders LLC grants - * this exception to all derivative works. AlliedModders LLC defines further - * exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007), - * or . - * - * Version: $Id$ - */ - -#ifndef _INCLUDE_SOURCEPAWN_JIT_X86_DLL_H_ -#define _INCLUDE_SOURCEPAWN_JIT_X86_DLL_H_ - -#include - -#if defined WIN32 -#define EXPORTFUNC extern "C" __declspec(dllexport) -#elif defined __GNUC__ -#if __GNUC__ >= 3 -#define EXPORTFUNC extern "C" __attribute__((visibility("default"))) -#else -#define EXPORTFUNC extern "C" -#endif //__GNUC__ >= 3 -#endif //defined __GNUC__ - -#endif //_INCLUDE_SOURCEPAWN_JIT_X86_DLL_H_ diff --git a/sourcepawn/vm/environment.cpp b/sourcepawn/vm/environment.cpp deleted file mode 100644 index e62753df..00000000 --- a/sourcepawn/vm/environment.cpp +++ /dev/null @@ -1,402 +0,0 @@ -// vim: set sts=2 ts=8 sw=2 tw=99 et: -// -// Copyright (C) 2006-2015 AlliedModders LLC -// -// This file is part of SourcePawn. SourcePawn is free software: you can -// redistribute it and/or modify it under the terms of the GNU General Public -// License as published by the Free Software Foundation, either version 3 of -// the License, or (at your option) any later version. -// -// You should have received a copy of the GNU General Public License along with -// SourcePawn. If not, see http://www.gnu.org/licenses/. -// -#include "environment.h" -#include "x86/jit_x86.h" -#include "watchdog_timer.h" -#include "api.h" -#include "code-stubs.h" -#include "watchdog_timer.h" -#include - -using namespace sp; -using namespace SourcePawn; - -static Environment *sEnvironment = nullptr; - -Environment::Environment() - : debugger_(nullptr), - exception_code_(SP_ERROR_NONE), - profiler_(nullptr), - jit_enabled_(true), - profiling_enabled_(false), - code_pool_(nullptr), - top_(nullptr) -{ -} - -Environment::~Environment() -{ -} - -Environment * -Environment::New() -{ - assert(!sEnvironment); - if (sEnvironment) - return nullptr; - - sEnvironment = new Environment(); - if (!sEnvironment->Initialize()) { - delete sEnvironment; - sEnvironment = nullptr; - return nullptr; - } - - return sEnvironment; -} - -Environment * -Environment::get() -{ - return sEnvironment; -} - -bool -Environment::Initialize() -{ - api_v1_ = new SourcePawnEngine(); - api_v2_ = new SourcePawnEngine2(); - code_stubs_ = new CodeStubs(this); - watchdog_timer_ = new WatchdogTimer(this); - - if ((code_pool_ = Knight::KE_CreateCodeCache()) == nullptr) - return false; - - // Safe to initialize code now that we have the code cache. - if (!code_stubs_->Initialize()) - return false; - - return true; -} - -void -Environment::Shutdown() -{ - watchdog_timer_->Shutdown(); - code_stubs_->Shutdown(); - Knight::KE_DestroyCodeCache(code_pool_); - - assert(sEnvironment == this); - sEnvironment = nullptr; -} - -void -Environment::EnableProfiling() -{ - profiling_enabled_ = !!profiler_; -} - -void -Environment::DisableProfiling() -{ - profiling_enabled_ = false; -} - -bool -Environment::InstallWatchdogTimer(int timeout_ms) -{ - return watchdog_timer_->Initialize(timeout_ms); -} - -ISourcePawnEngine * -Environment::APIv1() -{ - return api_v1_; -} - -ISourcePawnEngine2 * -Environment::APIv2() -{ - return api_v2_; -} - -static const char *sErrorMsgTable[] = -{ - NULL, - "Unrecognizable file format", - "Decompressor was not found", - "Not enough space on the heap", - "Invalid parameter or parameter type", - "Invalid plugin address", - "Object or index not found", - "Invalid index or index not found", - "Not enough space on the stack", - "Debug section not found or debug not enabled", - "Invalid instruction", - "Invalid memory access", - "Stack went below stack boundary", - "Heap went below heap boundary", - "Divide by zero", - "Array index is out of bounds", - "Instruction contained invalid parameter", - "Stack memory leaked by native", - "Heap memory leaked by native", - "Dynamic array is too big", - "Tracker stack is out of bounds", - "Native is not bound", - "Maximum number of parameters reached", - "Native detected error", - "Plugin not runnable", - "Call was aborted", - "Plugin format is too old", - "Plugin format is too new", - "Out of memory", - "Integer overflow", - "Script execution timed out", - "Custom error", - "Fatal error" -}; - -const char * -Environment::GetErrorString(int error) -{ - if (error < 1 || error > int(sizeof(sErrorMsgTable) / sizeof(sErrorMsgTable[0]))) - return NULL; - return sErrorMsgTable[error]; -} - -void * -Environment::AllocateCode(size_t size) -{ - return Knight::KE_AllocCode(code_pool_, size); -} - -void -Environment::FreeCode(void *code) -{ - Knight::KE_FreeCode(code_pool_, code); -} - -void -Environment::RegisterRuntime(PluginRuntime *rt) -{ - mutex_.AssertCurrentThreadOwns(); - runtimes_.append(rt); -} - -void -Environment::DeregisterRuntime(PluginRuntime *rt) -{ - mutex_.AssertCurrentThreadOwns(); - runtimes_.remove(rt); -} - -static inline void -SwapLoopEdge(uint8_t *code, LoopEdge &e) -{ - int32_t *loc = reinterpret_cast(code + e.offset - 4); - int32_t new_disp32 = e.disp32; - e.disp32 = *loc; - *loc = new_disp32; -} - -void -Environment::PatchAllJumpsForTimeout() -{ - mutex_.AssertCurrentThreadOwns(); - for (ke::InlineList::iterator iter = runtimes_.begin(); iter != runtimes_.end(); iter++) { - PluginRuntime *rt = *iter; - for (size_t i = 0; i < rt->NumJitFunctions(); i++) { - CompiledFunction *fun = rt->GetJitFunction(i); - uint8_t *base = reinterpret_cast(fun->GetEntryAddress()); - - for (size_t j = 0; j < fun->NumLoopEdges(); j++) - SwapLoopEdge(base, fun->GetLoopEdge(j)); - } - } -} - -void -Environment::UnpatchAllJumpsFromTimeout() -{ - mutex_.AssertCurrentThreadOwns(); - for (ke::InlineList::iterator iter = runtimes_.begin(); iter != runtimes_.end(); iter++) { - PluginRuntime *rt = *iter; - for (size_t i = 0; i < rt->NumJitFunctions(); i++) { - CompiledFunction *fun = rt->GetJitFunction(i); - uint8_t *base = reinterpret_cast(fun->GetEntryAddress()); - - for (size_t j = 0; j < fun->NumLoopEdges(); j++) - SwapLoopEdge(base, fun->GetLoopEdge(j)); - } - } -} - -int -Environment::Invoke(PluginRuntime *runtime, CompiledFunction *fn, cell_t *result) -{ - // Must be in an invoke frame. - assert(top_ && top_->cx() == runtime->GetBaseContext()); - - PluginContext *cx = runtime->GetBaseContext(); - - InvokeStubFn invoke = code_stubs_->InvokeStub(); - return invoke(cx, fn->GetEntryAddress(), result); -} - -void -Environment::ReportError(int code) -{ - const char *message = GetErrorString(code); - if (!message) { - char buffer[255]; - UTIL_Format(buffer, sizeof(buffer), "Unknown error code %d", code); - ReportError(code, buffer); - } else { - ReportError(code, message); - } -} - -class ErrorReport : public SourcePawn::IErrorReport -{ - public: - ErrorReport(int code, const char *message, PluginContext *cx) - : code_(code), - message_(message), - context_(cx) - {} - - const char *Message() const KE_OVERRIDE { - return message_; - } - bool IsFatal() const KE_OVERRIDE { - switch (code_) { - case SP_ERROR_HEAPLOW: - case SP_ERROR_INVALID_ADDRESS: - case SP_ERROR_STACKLOW: - case SP_ERROR_INVALID_INSTRUCTION: - case SP_ERROR_MEMACCESS: - case SP_ERROR_STACKMIN: - case SP_ERROR_HEAPMIN: - case SP_ERROR_INSTRUCTION_PARAM: - case SP_ERROR_STACKLEAK: - case SP_ERROR_HEAPLEAK: - case SP_ERROR_TRACKER_BOUNDS: - case SP_ERROR_PARAMS_MAX: - case SP_ERROR_ABORTED: - case SP_ERROR_OUT_OF_MEMORY: - case SP_ERROR_FATAL: - return true; - default: - return false; - } - } - IPluginContext *Context() const KE_OVERRIDE { - return context_; - } - - private: - int code_; - const char *message_; - PluginContext *context_; -}; - -void -Environment::ReportErrorVA(const char *fmt, va_list ap) -{ - ReportErrorVA(SP_ERROR_USER, fmt, ap); -} - -void -Environment::ReportErrorVA(int code, const char *fmt, va_list ap) -{ - // :TODO: right-size the string rather than rely on this buffer. - char buffer[1024]; - UTIL_FormatVA(buffer, sizeof(buffer), fmt, ap); - ReportError(code, buffer); -} - -void -Environment::ReportErrorFmt(int code, const char *message, ...) -{ - va_list ap; - va_start(ap, message); - ReportErrorVA(code, message, ap); - va_end(ap); -} - -void -Environment::ReportError(int code, const char *message) -{ - FrameIterator iter; - ErrorReport report(code, message, top_ ? top_->cx() : nullptr); - - // If this fires, someone forgot to propagate an error. - assert(!hasPendingException()); - - // Save the exception state. - if (eh_top_) { - exception_code_ = code; - UTIL_Format(exception_message_, sizeof(exception_message_), "%s", message); - } - - // For now, we always report exceptions even if they might be handled. - if (debugger_) - debugger_->ReportError(report, iter); -} - -void -Environment::EnterExceptionHandlingScope(ExceptionHandler *handler) -{ - handler->next_ = eh_top_; - eh_top_ = handler; -} - -void -Environment::LeaveExceptionHandlingScope(ExceptionHandler *handler) -{ - assert(handler == eh_top_); - eh_top_ = eh_top_->next_; - - // To preserve compatibility with older API, we clear the exception state - // when there is no EH handler. - if (!eh_top_ || handler->catch_) - exception_code_ = SP_ERROR_NONE; -} - -bool -Environment::HasPendingException(const ExceptionHandler *handler) -{ - // Note here and elsewhere - this is not a sanity assert. In the future, the - // API may need to query the handler. - assert(handler == eh_top_); - return hasPendingException(); -} - -const char * -Environment::GetPendingExceptionMessage(const ExceptionHandler *handler) -{ - // Note here and elsewhere - this is not a sanity assert. In the future, the - // API may need to query the handler. - assert(handler == eh_top_); - assert(HasPendingException(handler)); - return exception_message_; -} - -bool -Environment::hasPendingException() const -{ - return exception_code_ != SP_ERROR_NONE; -} - -void -Environment::clearPendingException() -{ - exception_code_ = SP_ERROR_NONE; -} - -int -Environment::getPendingExceptionCode() const -{ - return exception_code_; -} diff --git a/sourcepawn/vm/environment.h b/sourcepawn/vm/environment.h deleted file mode 100644 index 7e6f8cfe..00000000 --- a/sourcepawn/vm/environment.h +++ /dev/null @@ -1,200 +0,0 @@ -// vim: set sts=2 ts=8 sw=2 tw=99 et: -// -// Copyright (C) 2006-2015 AlliedModders LLC -// -// This file is part of SourcePawn. SourcePawn is free software: you can -// redistribute it and/or modify it under the terms of the GNU General Public -// License as published by the Free Software Foundation, either version 3 of -// the License, or (at your option) any later version. -// -// You should have received a copy of the GNU General Public License along with -// SourcePawn. If not, see http://www.gnu.org/licenses/. -// -#ifndef _include_sourcepawn_vm_environment_h_ -#define _include_sourcepawn_vm_environment_h_ - -#include -#include // Replace with am-cxx later. -#include -#include -#include "code-allocator.h" -#include "plugin-runtime.h" -#include "stack-frames.h" - -namespace sp { - -using namespace SourcePawn; - -class PluginRuntime; -class CodeStubs; -class WatchdogTimer; - -// An Environment encapsulates everything that's needed to load and run -// instances of plugins on a single thread. There can be at most one -// environment per thread. -// -// Currently, the VM is single threaded in that no more than one -// Environment can be created per process. -class Environment : public ISourcePawnEnvironment -{ - public: - Environment(); - ~Environment(); - - static Environment *New(); - - void Shutdown() KE_OVERRIDE; - ISourcePawnEngine *APIv1() KE_OVERRIDE; - ISourcePawnEngine2 *APIv2() KE_OVERRIDE; - int ApiVersion() KE_OVERRIDE { - return SOURCEPAWN_API_VERSION; - } - - // Access the current Environment. - static Environment *get(); - - bool InstallWatchdogTimer(int timeout_ms); - - void EnterExceptionHandlingScope(ExceptionHandler *handler) KE_OVERRIDE; - void LeaveExceptionHandlingScope(ExceptionHandler *handler) KE_OVERRIDE; - bool HasPendingException(const ExceptionHandler *handler) KE_OVERRIDE; - const char *GetPendingExceptionMessage(const ExceptionHandler *handler) KE_OVERRIDE; - - // Runtime functions. - const char *GetErrorString(int err); - void ReportError(int code); - void ReportError(int code, const char *message); - void ReportErrorFmt(int code, const char *message, ...); - void ReportErrorVA(const char *fmt, va_list ap); - void ReportErrorVA(int code, const char *fmt, va_list ap); - - // Allocate and free executable memory. - void *AllocateCode(size_t size); - void FreeCode(void *code); - CodeStubs *stubs() { - return code_stubs_; - } - - // Runtime management. - void RegisterRuntime(PluginRuntime *rt); - void DeregisterRuntime(PluginRuntime *rt); - void PatchAllJumpsForTimeout(); - void UnpatchAllJumpsFromTimeout(); - ke::Mutex *lock() { - return &mutex_; - } - int Invoke(PluginRuntime *runtime, CompiledFunction *fn, cell_t *result); - - // Helpers. - void SetProfiler(IProfilingTool *profiler) { - profiler_ = profiler; - } - IProfilingTool *profiler() const { - return profiler_; - } - bool IsProfilingEnabled() const { - return profiling_enabled_; - } - void EnableProfiling(); - void DisableProfiling(); - - void SetJitEnabled(bool enabled) { - } - bool IsJitEnabled() const { - return jit_enabled_; - } - void SetDebugger(IDebugListener *debugger) { - debugger_ = debugger; - } - IDebugListener *debugger() const { - return debugger_; - } - - WatchdogTimer *watchdog() const { - return watchdog_timer_; - } - - bool hasPendingException() const; - void clearPendingException(); - int getPendingExceptionCode() const; - - // These are indicators used for the watchdog timer. - uintptr_t FrameId() const { - return frame_id_; - } - bool RunningCode() const { - return !!top_; - } - void enterInvoke(InvokeFrame *frame) { - if (!top_) - frame_id_++; - top_ = frame; - } - void leaveInvoke() { - exit_frame_ = top_->prev_exit_frame(); - top_ = top_->prev(); - } - - InvokeFrame *top() const { - return top_; - } - const ExitFrame &exit_frame() const { - return exit_frame_; - } - - public: - static inline size_t offsetOfTopFrame() { - return offsetof(Environment, top_); - } - static inline size_t offsetOfExceptionCode() { - return offsetof(Environment, exception_code_); - } - - private: - bool Initialize(); - - private: - ke::AutoPtr api_v1_; - ke::AutoPtr api_v2_; - ke::AutoPtr watchdog_timer_; - ke::Mutex mutex_; - - IDebugListener *debugger_; - ExceptionHandler *eh_top_; - int exception_code_; - char exception_message_[1024]; - - IProfilingTool *profiler_; - bool jit_enabled_; - bool profiling_enabled_; - - Knight::KeCodeCache *code_pool_; - ke::InlineList runtimes_; - - uintptr_t frame_id_; - - ke::AutoPtr code_stubs_; - - InvokeFrame *top_; - ExitFrame exit_frame_; -}; - -class EnterProfileScope -{ - public: - EnterProfileScope(const char *group, const char *name) - { - if (Environment::get()->IsProfilingEnabled()) - Environment::get()->profiler()->EnterScope(group, name); - } - - ~EnterProfileScope() - { - if (Environment::get()->IsProfilingEnabled()) - Environment::get()->profiler()->LeaveScope(); - } -}; - -} // namespace sp - -#endif // _include_sourcepawn_vm_environment_h_ diff --git a/sourcepawn/vm/file-utils.cpp b/sourcepawn/vm/file-utils.cpp deleted file mode 100644 index f712a61e..00000000 --- a/sourcepawn/vm/file-utils.cpp +++ /dev/null @@ -1,52 +0,0 @@ -// vim: set sts=2 ts=8 sw=2 tw=99 et: -// -// Copyright (C) 2004-2015 AlliedModers LLC -// -// This file is part of SourcePawn. SourcePawn is licensed under the GNU -// General Public License, version 3.0 (GPL). If a copy of the GPL was not -// provided with this file, you can obtain it here: -// http://www.gnu.org/licenses/gpl.html -// -#include -#include -#include "file-utils.h" - -using namespace sp; - -FileType -sp::DetectFileType(FILE *fp) -{ - uint32_t magic = 0; - if (fread(&magic, sizeof(uint32_t), 1, fp) != 1) - return FileType::UNKNOWN; - - if (magic == SmxConsts::FILE_MAGIC) - return FileType::SPFF; - - return FileType::UNKNOWN; -} - -FileReader::FileReader(FILE *fp) - : length_(0) -{ - if (fseek(fp, 0, SEEK_END) != 0) - return; - long size = ftell(fp); - if (size < 0) - return; - if (fseek(fp, 0, SEEK_SET) != 0) - return; - - ke::AutoArray bytes(new uint8_t[size]); - if (!bytes || fread(bytes, sizeof(uint8_t), size, fp) != (size_t)size) - return; - - buffer_ = bytes.take(); - length_ = size; -} - -FileReader::FileReader(ke::AutoArray &buffer, size_t length) - : buffer_(buffer.take()), - length_(length) -{ -} diff --git a/sourcepawn/vm/file-utils.h b/sourcepawn/vm/file-utils.h deleted file mode 100644 index 83c49267..00000000 --- a/sourcepawn/vm/file-utils.h +++ /dev/null @@ -1,47 +0,0 @@ -// vim: set sts=2 ts=8 sw=2 tw=99 et: -// -// Copyright (C) 2004-2015 AlliedModers LLC -// -// This file is part of SourcePawn. SourcePawn is licensed under the GNU -// General Public License, version 3.0 (GPL). If a copy of the GPL was not -// provided with this file, you can obtain it here: -// http://www.gnu.org/licenses/gpl.html -// -#ifndef _include_sourcepawn_file_parser_h_ -#define _include_sourcepawn_file_parser_h_ - -#include -#include - -namespace sp { - -enum class FileType { - UNKNOWN, - AMX, - AMXMODX, - SPFF -}; - -FileType DetectFileType(FILE *fp); - -class FileReader -{ - public: - FileReader(FILE *fp); - FileReader(ke::AutoArray &buffer, size_t length); - - const uint8_t *buffer() const { - return buffer_; - } - size_t length() const { - return length_; - } - - protected: - ke::AutoArray buffer_; - size_t length_; -}; - -} // namespace sp - -#endif // _include_sourcepawn_file_parser_h_ diff --git a/sourcepawn/vm/legacy-image.h b/sourcepawn/vm/legacy-image.h deleted file mode 100644 index 725eb665..00000000 --- a/sourcepawn/vm/legacy-image.h +++ /dev/null @@ -1,138 +0,0 @@ -// vim: set sts=2 ts=8 sw=2 tw=99 et: -// -// Copyright (C) 2006-2015 AlliedModders LLC -// -// This file is part of SourcePawn. SourcePawn is free software: you can -// redistribute it and/or modify it under the terms of the GNU General Public -// License as published by the Free Software Foundation, either version 3 of -// the License, or (at your option) any later version. -// -// You should have received a copy of the GNU General Public License along with -// SourcePawn. If not, see http://www.gnu.org/licenses/. -// -#ifndef _include_sourcepawn_vm_legacy_image_h_ -#define _include_sourcepawn_vm_legacy_image_h_ - -#include - -namespace sp { - -// A LegacyImage is an abstraction layer for reading the various types of -// binaries that expose Pawn or SourcePawn v1 pcode. -class LegacyImage -{ - public: - virtual ~LegacyImage() - {} - - enum class CodeVersion { - Unknown, - SP_1_0, - SP_1_1 - }; - - struct Code { - const uint8_t *bytes; - size_t length; - CodeVersion version; - }; - struct Data { - const uint8_t *bytes; - size_t length; - }; - - // (Almost) everything needed to implement the AMX and SPVM API. - virtual Code DescribeCode() const = 0; - virtual Data DescribeData() const = 0; - virtual size_t NumNatives() const = 0; - virtual const char *GetNative(size_t index) const = 0; - virtual bool FindNative(const char *name, size_t *indexp) const = 0; - virtual size_t NumPublics() const = 0; - virtual void GetPublic(size_t index, uint32_t *offsetp, const char **namep) const = 0; - virtual bool FindPublic(const char *name, size_t *indexp) const = 0; - virtual size_t NumPubvars() const = 0; - virtual void GetPubvar(size_t index, uint32_t *offsetp, const char **namep) const = 0; - virtual bool FindPubvar(const char *name, size_t *indexp) const = 0; - virtual size_t HeapSize() const = 0; - virtual size_t ImageSize() const = 0; - virtual const char *LookupFile(uint32_t code_offset) = 0; - virtual const char *LookupFunction(uint32_t code_offset) = 0; - virtual bool LookupLine(uint32_t code_offset, uint32_t *line) = 0; -}; - -class EmptyImage : public LegacyImage -{ - public: - EmptyImage(size_t heapSize) - : heap_size_(heapSize) - { - heap_size_ += sizeof(uint32_t); - heap_size_ -= heap_size_ % sizeof(uint32_t); - memset(data_, 0, sizeof(data_)); - memset(code_, 0, sizeof(code_)); - } - - public: - Code DescribeCode() const KE_OVERRIDE { - Code out; - out.bytes = code_; - out.length = sizeof(code_); - out.version = CodeVersion::SP_1_1; - return out; - } - Data DescribeData() const KE_OVERRIDE { - Data out; - out.bytes = data_; - out.length = sizeof(data_); - return out; - } - size_t NumNatives() const KE_OVERRIDE { - return 0; - } - const char *GetNative(size_t index) const KE_OVERRIDE { - return nullptr; - } - bool FindNative(const char *name, size_t *indexp) const KE_OVERRIDE { - return false; - } - size_t NumPublics() const KE_OVERRIDE { - return 0; - } - void GetPublic(size_t index, uint32_t *offsetp, const char **namep) const KE_OVERRIDE { - } - bool FindPublic(const char *name, size_t *indexp) const KE_OVERRIDE { - return false; - } - size_t NumPubvars() const KE_OVERRIDE { - return 0; - } - void GetPubvar(size_t index, uint32_t *offsetp, const char **namep) const KE_OVERRIDE { - } - bool FindPubvar(const char *name, size_t *indexp) const KE_OVERRIDE { - return false; - } - size_t HeapSize() const KE_OVERRIDE { - return heap_size_; - } - size_t ImageSize() const KE_OVERRIDE { - return 0; - } - const char *LookupFile(uint32_t code_offset) KE_OVERRIDE { - return nullptr; - } - const char *LookupFunction(uint32_t code_offset) { - return nullptr; - } - bool LookupLine(uint32_t code_offset, uint32_t *line) KE_OVERRIDE { - return false; - } - - private: - size_t heap_size_; - uint8_t data_[4]; - uint8_t code_[4]; -}; - -} - -#endif // _include_sourcepawn_vm_legacy_image_h_ diff --git a/sourcepawn/vm/md5/md5.cpp b/sourcepawn/vm/md5/md5.cpp deleted file mode 100644 index 8ca10ebc..00000000 --- a/sourcepawn/vm/md5/md5.cpp +++ /dev/null @@ -1,475 +0,0 @@ -// MD5.CC - source code for the C++/object oriented translation and -// modification of MD5. - -// Translation and modification (c) 1995 by Mordechai T. Abzug - -// This translation/ modification is provided "as is," without express or -// implied warranty of any kind. - -// The translator/ modifier does not claim (1) that MD5 will do what you think -// it does; (2) that this translation/ modification is accurate; or (3) that -// this software is "merchantible." (Language for this disclaimer partially -// copied from the disclaimer below). - -/* based on: - - MD5C.C - RSA Data Security, Inc., MD5 message-digest algorithm - MDDRIVER.C - test driver for MD2, MD4 and MD5 - - - Copyright (C) 1991-2, RSA Data Security, Inc. Created 1991. All -rights reserved. - -License to copy and use this software is granted provided that it -is identified as the "RSA Data Security, Inc. MD5 Message-Digest -Algorithm" in all material mentioning or referencing this software -or this function. - -License is also granted to make and use derivative works provided -that such works are identified as "derived from the RSA Data -Security, Inc. MD5 Message-Digest Algorithm" in all material -mentioning or referencing the derived work. - -RSA Data Security, Inc. makes no representations concerning either -the merchantability of this software or the suitability of this -software for any particular purpose. It is provided "as is" -without express or implied warranty of any kind. - -These notices must be retained in any copies of any part of this -documentation and/or software. - - */ - -#include "md5.h" - -#include -#include - -// MD5 simple initialization method - -MD5::MD5(){ - - init(); - -} - - -// MD5 block update operation. Continues an MD5 message-digest -// operation, processing another message block, and updating the -// context. - -void MD5::update (const uint1 *input, uint4 input_length) { - - uint4 input_index, buffer_index; - uint4 buffer_space; // how much space is left in buffer - - if (finalized){ // so we can't update! - /*cerr << "MD5::update: Can't update a finalized digest!" << endl;*/ - return; - } - - // Compute number of bytes mod 64 - buffer_index = (unsigned int)((count[0] >> 3) & 0x3F); - - // Update number of bits - if ( (count[0] += ((uint4) input_length << 3))<((uint4) input_length << 3) ) - count[1]++; - - count[1] += ((uint4)input_length >> 29); - - - buffer_space = 64 - buffer_index; // how much space is left in buffer - - // Transform as many times as possible. - if (input_length >= buffer_space) { // ie. we have enough to fill the buffer - // fill the rest of the buffer and transform - memcpy (buffer + buffer_index, input, buffer_space); - transform (buffer); - - // now, transform each 64-byte piece of the input, bypassing the buffer - for (input_index = buffer_space; input_index + 63 < input_length; - input_index += 64) - transform (input+input_index); - - buffer_index = 0; // so we can buffer remaining - } - else - input_index=0; // so we can buffer the whole input - - - // and here we do the buffering: - memcpy(buffer+buffer_index, input+input_index, input_length-input_index); -} - - - -// MD5 update for files. -// Like above, except that it works on files (and uses above as a primitive.) - -void MD5::update(FILE *file){ - - unsigned char buffer[1024]; - int len; - - while ((len=fread(buffer, 1, 1024, file))) - update(buffer, len); - - fclose (file); - -} - - -// MD5 finalization. Ends an MD5 message-digest operation, writing the -// the message digest and zeroizing the context. - - -void MD5::finalize (){ - - unsigned char bits[8]; - unsigned int index, padLen; - static uint1 PADDING[64]={ - 0x80, 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 - }; - - if (finalized){ - /* cerr << "MD5::finalize: Already finalized this digest!" << endl;*/ - return; - } - - // Save number of bits - encode (bits, count, 8); - - // Pad out to 56 mod 64. - index = (uint4) ((count[0] >> 3) & 0x3f); - padLen = (index < 56) ? (56 - index) : (120 - index); - update (PADDING, padLen); - - // Append length (before padding) - update (bits, 8); - - // Store state in digest - encode (digest, state, 16); - - // Zeroize sensitive information - memset (buffer, 0, sizeof(*buffer)); - - finalized=1; - -} - - - - -MD5::MD5(FILE *file){ - - init(); // must be called be all constructors - update(file); - finalize (); -} - -unsigned char *MD5::raw_digest(){ - - if (!finalized){ -/* cerr << "MD5::raw_digest: Can't get digest if you haven't "<< - "finalized the digest!" <> 8) & 0xff); - output[j+2] = (uint1) ((input[i] >> 16) & 0xff); - output[j+3] = (uint1) ((input[i] >> 24) & 0xff); - } -} - - - - -// Decodes input (unsigned char) into output (UINT4). Assumes len is -// a multiple of 4. -void MD5::decode (uint4 *output, const uint1 *input, uint4 len){ - - unsigned int i, j; - - for (i = 0, j = 0; j < len; i++, j += 4) - output[i] = ((uint4)input[j]) | (((uint4)input[j+1]) << 8) | - (((uint4)input[j+2]) << 16) | (((uint4)input[j+3]) << 24); -} - - - - - -// Note: Replace "for loop" with standard memcpy if possible. -void MD5::memcpy (uint1 *output, const uint1 *input, uint4 len){ - - unsigned int i; - - for (i = 0; i < len; i++) - output[i] = input[i]; -} - - - -// Note: Replace "for loop" with standard memset if possible. -void MD5::memset (uint1 *output, uint1 value, uint4 len){ - - unsigned int i; - - for (i = 0; i < len; i++) - output[i] = value; -} - - - -// ROTATE_LEFT rotates x left n bits. - -inline unsigned int MD5::rotate_left (uint4 x, uint4 n){ - return (x << n) | (x >> (32-n)) ; -} - - - - -// F, G, H and I are basic MD5 functions. - -inline unsigned int MD5::F (uint4 x, uint4 y, uint4 z){ - return (x & y) | (~x & z); -} - -inline unsigned int MD5::G (uint4 x, uint4 y, uint4 z){ - return (x & z) | (y & ~z); -} - -inline unsigned int MD5::H (uint4 x, uint4 y, uint4 z){ - return x ^ y ^ z; -} - -inline unsigned int MD5::I (uint4 x, uint4 y, uint4 z){ - return y ^ (x | ~z); -} - - - -// FF, GG, HH, and II transformations for rounds 1, 2, 3, and 4. -// Rotation is separate from addition to prevent recomputation. - - -inline void MD5::FF(uint4& a, uint4 b, uint4 c, uint4 d, uint4 x, - uint4 s, uint4 ac){ - a += F(b, c, d) + x + ac; - a = rotate_left (a, s) +b; -} - -inline void MD5::GG(uint4& a, uint4 b, uint4 c, uint4 d, uint4 x, - uint4 s, uint4 ac){ - a += G(b, c, d) + x + ac; - a = rotate_left (a, s) +b; -} - -inline void MD5::HH(uint4& a, uint4 b, uint4 c, uint4 d, uint4 x, - uint4 s, uint4 ac){ - a += H(b, c, d) + x + ac; - a = rotate_left (a, s) +b; -} - -inline void MD5::II(uint4& a, uint4 b, uint4 c, uint4 d, uint4 x, - uint4 s, uint4 ac){ - a += I(b, c, d) + x + ac; - a = rotate_left (a, s) +b; -} diff --git a/sourcepawn/vm/md5/md5.h b/sourcepawn/vm/md5/md5.h deleted file mode 100644 index b90dabb5..00000000 --- a/sourcepawn/vm/md5/md5.h +++ /dev/null @@ -1,106 +0,0 @@ -// MD5.CC - source code for the C++/object oriented translation and -// modification of MD5. - -// Translation and modification (c) 1995 by Mordechai T. Abzug - -// This translation/ modification is provided "as is," without express or -// implied warranty of any kind. - -// The translator/ modifier does not claim (1) that MD5 will do what you think -// it does; (2) that this translation/ modification is accurate; or (3) that -// this software is "merchantible." (Language for this disclaimer partially -// copied from the disclaimer below). - -/* based on: - - MD5.H - header file for MD5C.C - MDDRIVER.C - test driver for MD2, MD4 and MD5 - - Copyright (C) 1991-2, RSA Data Security, Inc. Created 1991. All -rights reserved. - -License to copy and use this software is granted provided that it -is identified as the "RSA Data Security, Inc. MD5 Message-Digest -Algorithm" in all material mentioning or referencing this software -or this function. - -License is also granted to make and use derivative works provided -that such works are identified as "derived from the RSA Data -Security, Inc. MD5 Message-Digest Algorithm" in all material -mentioning or referencing the derived work. - -RSA Data Security, Inc. makes no representations concerning either -the merchantability of this software or the suitability of this -software for any particular purpose. It is provided "as is" -without express or implied warranty of any kind. - -These notices must be retained in any copies of any part of this -documentation and/or software. - -*/ - -#include -//#include -//#include - -class MD5 { - -public: -// methods for controlled operation: - MD5 (); // simple initializer - void update (const unsigned char *input, unsigned int input_length); - void update (FILE *file); - void finalize (); - -// constructors for special circumstances. All these constructors finalize -// the MD5 context. - MD5 (unsigned char *string); // digest string, finalize - MD5 (FILE *file); // digest file, close, finalize - -// methods to acquire finalized result - unsigned char *raw_digest (); // digest as a 16-byte binary array - unsigned char *raw_digest(unsigned char buffer[16]); - char * hex_digest (); // digest as a 33-byte ascii-hex string - char * hex_digest (char buffer[33]); //same as above, passing buffer - - - -private: - -// first, some types: - typedef unsigned int uint4; // assumes integer is 4 words long - typedef unsigned short int uint2; // assumes short integer is 2 words long - typedef unsigned char uint1; // assumes char is 1 word long - -// next, the private data: - uint4 state[4]; - uint4 count[2]; // number of *bits*, mod 2^64 - uint1 buffer[64]; // input buffer - uint1 digest[16]; - uint1 finalized; - -// last, the private methods, mostly static: - void init (); // called by all constructors - void transform (const uint1 *buffer); // does the real update work. Note - // that length is implied to be 64. - - static void encode (uint1 *dest, const uint4 *src, uint4 length); - static void decode (uint4 *dest, const uint1 *src, uint4 length); - static void memcpy (uint1 *dest, const uint1 *src, uint4 length); - static void memset (uint1 *start, uint1 val, uint4 length); - - static inline uint4 rotate_left (uint4 x, uint4 n); - static inline uint4 F (uint4 x, uint4 y, uint4 z); - static inline uint4 G (uint4 x, uint4 y, uint4 z); - static inline uint4 H (uint4 x, uint4 y, uint4 z); - static inline uint4 I (uint4 x, uint4 y, uint4 z); - static inline void FF (uint4& a, uint4 b, uint4 c, uint4 d, uint4 x, - uint4 s, uint4 ac); - static inline void GG (uint4& a, uint4 b, uint4 c, uint4 d, uint4 x, - uint4 s, uint4 ac); - static inline void HH (uint4& a, uint4 b, uint4 c, uint4 d, uint4 x, - uint4 s, uint4 ac); - static inline void II (uint4& a, uint4 b, uint4 c, uint4 d, uint4 x, - uint4 s, uint4 ac); - -}; diff --git a/sourcepawn/vm/opcodes.cpp b/sourcepawn/vm/opcodes.cpp deleted file mode 100644 index 7876e008..00000000 --- a/sourcepawn/vm/opcodes.cpp +++ /dev/null @@ -1,141 +0,0 @@ -/** - * vim: set ts=8 sw=2 tw=99 sts=2 et: - * ============================================================================= - * SourceMod - * Copyright _(C) 2004-2008 AlliedModders LLC. All rights reserved. - * ============================================================================= - * - * This program is free software; you can redistribute it and/or modify it under - * the terms of the GNU General Public License), version 3.0), as published by the - * Free Software Foundation. - * - * This program is distributed in the hope that it will be useful), but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS - * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more - * details. - * - * You should have received a copy of the GNU General Public License along with - * this program. If not), see . - * - * As a special exception), AlliedModders LLC gives you permission to link the - * code of this program _(as well as its derivative works) to "Half-Life 2)," the - * "Source Engine)," the "SourcePawn JIT)," and any Game MODs that run on software - * by the Valve Corporation. You must obey the GNU General Public License in - * all respects for all other code used. Additionally), AlliedModders LLC grants - * this exception to all derivative works. AlliedModders LLC defines further - * exceptions), found in LICENSE.txt _(as of this writing), version JULY-31-2007)), - * or . - * - * Version: $Id$ - */ -#include "opcodes.h" - -using namespace sp; -using namespace SourcePawn; - -const char *OpcodeNames[] = { -#define _(op, text) text, - OPCODE_LIST(_) -#undef _ - NULL -}; - -#ifdef JIT_SPEW -void -SourcePawn::SpewOpcode(const sp_plugin_t *plugin, cell_t *start, cell_t *cip) -{ - fprintf(stdout, " [%05d:%04d]", cip - (cell_t *)plugin->pcode, cip - start); - - if (*cip >= OPCODES_TOTAL) { - fprintf(stdout, " unknown-opcode\n"); - return; - } - - OPCODE op = (OPCODE)*cip; - fprintf(stdout, " %s ", OpcodeNames[op]); - - switch (op) { - case OP_PUSH_C: - case OP_PUSH_ADR: - case OP_SHL_C_PRI: - case OP_SHL_C_ALT: - case OP_SHR_C_PRI: - case OP_SHR_C_ALT: - case OP_ADD_C: - case OP_SMUL_C: - case OP_EQ_C_PRI: - case OP_EQ_C_ALT: - case OP_TRACKER_PUSH_C: - case OP_STACK: - case OP_PUSH_S: - case OP_HEAP: - case OP_GENARRAY: - case OP_GENARRAY_Z: - case OP_CONST_PRI: - case OP_CONST_ALT: - fprintf(stdout, "%d", cip[1]); - break; - - case OP_JUMP: - case OP_JZER: - case OP_JNZ: - case OP_JEQ: - case OP_JNEQ: - case OP_JSLESS: - case OP_JSGRTR: - case OP_JSGEQ: - case OP_JSLEQ: - fprintf(stdout, "%05d:%04d", - cip[1] / 4, - ((cell_t *)plugin->pcode + cip[1] / 4) - start); - break; - - case OP_SYSREQ_C: - case OP_SYSREQ_N: - { - uint32_t index = cip[1]; - if (index < plugin->num_natives) - fprintf(stdout, "%s", plugin->natives[index].name); - if (op == OP_SYSREQ_N) - fprintf(stdout, " ; (%d args, index %d)", cip[2], index); - else - fprintf(stdout, " ; (index %d)", index); - break; - } - - case OP_PUSH2_C: - case OP_PUSH2: - case OP_PUSH2_S: - case OP_PUSH2_ADR: - fprintf(stdout, "%d, %d", cip[1], cip[2]); - break; - - case OP_PUSH3_C: - case OP_PUSH3: - case OP_PUSH3_S: - case OP_PUSH3_ADR: - fprintf(stdout, "%d, %d, %d", cip[1], cip[2], cip[3]); - break; - - case OP_PUSH4_C: - case OP_PUSH4: - case OP_PUSH4_S: - case OP_PUSH4_ADR: - fprintf(stdout, "%d, %d, %d, %d", cip[1], cip[2], cip[3], cip[4]); - break; - - case OP_PUSH5_C: - case OP_PUSH5: - case OP_PUSH5_S: - case OP_PUSH5_ADR: - fprintf(stdout, "%d, %d, %d, %d, %d", cip[1], cip[2], cip[3], cip[4], cip[5]); - break; - - default: - break; - } - - fprintf(stdout, "\n"); -} -#endif - diff --git a/sourcepawn/vm/opcodes.h b/sourcepawn/vm/opcodes.h deleted file mode 100644 index ff569832..00000000 --- a/sourcepawn/vm/opcodes.h +++ /dev/null @@ -1,40 +0,0 @@ -/** - * vim: set ts=8 sw=2 tw=99 sts=2 et: - * ============================================================================= - * SourceMod - * Copyright (C) 2004-2008 AlliedModders LLC. All rights reserved. - * ============================================================================= - * - * This program is free software; you can redistribute it and/or modify it under - * the terms of the GNU General Public License), version 3.0), as published by the - * Free Software Foundation. - * - * This program is distributed in the hope that it will be useful), but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS - * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more - * details. - * - * You should have received a copy of the GNU General Public License along with - * this program. If not), see . - * - * As a special exception), AlliedModders LLC gives you permission to link the - * code of this program (as well as its derivative works) to "Half-Life 2)," the - * "Source Engine)," the "SourcePawn JIT)," and any Game MODs that run on software - * by the Valve Corporation. You must obey the GNU General Public License in - * all respects for all other code used. Additionally), AlliedModders LLC grants - * this exception to all derivative works. AlliedModders LLC defines further - * exceptions), found in LICENSE.txt (as of this writing), version JULY-31-2007)), - * or . - * - * Version: $Id$ - */ - -#ifndef _INCLUDE_SOURCEPAWN_JIT_X86_OPCODES_H_ -#define _INCLUDE_SOURCEPAWN_JIT_X86_OPCODES_H_ - -#include - -namespace SourcePawn { -} - -#endif //_INCLUDE_SOURCEPAWN_JIT_X86_OPCODES_H_ diff --git a/sourcepawn/vm/plugin-context.cpp b/sourcepawn/vm/plugin-context.cpp deleted file mode 100644 index 7470c787..00000000 --- a/sourcepawn/vm/plugin-context.cpp +++ /dev/null @@ -1,953 +0,0 @@ -// vim: set sts=2 ts=8 sw=2 tw=99 et: -// -// Copyright (C) 2006-2015 AlliedModders LLC -// -// This file is part of SourcePawn. SourcePawn is free software: you can -// redistribute it and/or modify it under the terms of the GNU General Public -// License as published by the Free Software Foundation, either version 3 of -// the License, or (at your option) any later version. -// -// You should have received a copy of the GNU General Public License along with -// SourcePawn. If not, see http://www.gnu.org/licenses/. -// -#include -#include -#include -#include -#include -#include "plugin-context.h" -#include "watchdog_timer.h" -#include "x86/jit_x86.h" -#include "environment.h" -#include "compiled-function.h" - -using namespace sp; -using namespace SourcePawn; - -#define CELLBOUNDMAX (INT_MAX/sizeof(cell_t)) -#define STACKMARGIN ((cell_t)(16*sizeof(cell_t))) - -static const size_t kMinHeapSize = 16384; - -PluginContext::PluginContext(PluginRuntime *pRuntime) - : env_(Environment::get()), - m_pRuntime(pRuntime), - memory_(nullptr), - data_size_(m_pRuntime->data().length), - mem_size_(m_pRuntime->image()->HeapSize()), - m_pNullVec(nullptr), - m_pNullString(nullptr) -{ - // Compute and align a minimum memory amount. - if (mem_size_ < data_size_) - mem_size_ = data_size_; - mem_size_ = ke::Align(mem_size_, sizeof(cell_t)); - - // Add a minimum heap size if needed. - if (mem_size_ < data_size_ + kMinHeapSize) - mem_size_ = data_size_ + kMinHeapSize; - assert(ke::IsAligned(mem_size_, sizeof(cell_t))); - - hp_ = data_size_; - sp_ = mem_size_ - sizeof(cell_t); - frm_ = sp_; - - tracker_.pBase = (ucell_t *)malloc(1024); - tracker_.pCur = tracker_.pBase; - tracker_.size = 1024 / sizeof(cell_t); -} - -PluginContext::~PluginContext() -{ - free(tracker_.pBase); - delete[] memory_; -} - -bool -PluginContext::Initialize() -{ - memory_ = new uint8_t[mem_size_]; - if (!memory_) - return false; - memset(memory_ + data_size_, 0, mem_size_ - data_size_); - memcpy(memory_, m_pRuntime->data().bytes, data_size_); - - /* Initialize the null references */ - uint32_t index; - if (FindPubvarByName("NULL_VECTOR", &index) == SP_ERROR_NONE) { - sp_pubvar_t *pubvar; - GetPubvarByIndex(index, &pubvar); - m_pNullVec = pubvar->offs; - } else { - m_pNullVec = NULL; - } - - if (FindPubvarByName("NULL_STRING", &index) == SP_ERROR_NONE) { - sp_pubvar_t *pubvar; - GetPubvarByIndex(index, &pubvar); - m_pNullString = pubvar->offs; - } else { - m_pNullString = NULL; - } - - return true; -} - -IVirtualMachine * -PluginContext::GetVirtualMachine() -{ - return NULL; -} - -sp_context_t * -PluginContext::GetContext() -{ - return reinterpret_cast((IPluginContext * )this); -} - -bool -PluginContext::IsDebugging() -{ - return true; -} - -int -PluginContext::SetDebugBreak(void *newpfn, void *oldpfn) -{ - return SP_ERROR_ABORTED; -} - -IPluginDebugInfo * -PluginContext::GetDebugInfo() -{ - return NULL; -} - -int -PluginContext::Execute(uint32_t code_addr, cell_t *result) -{ - return SP_ERROR_ABORTED; -} - -cell_t -PluginContext::ThrowNativeErrorEx(int error, const char *msg, ...) -{ - va_list ap; - va_start(ap, msg); - env_->ReportErrorVA(error, msg, ap); - va_end(ap); - return 0; -} - -cell_t -PluginContext::ThrowNativeError(const char *msg, ...) -{ - va_list ap; - va_start(ap, msg); - env_->ReportErrorVA(SP_ERROR_NATIVE, msg, ap); - va_end(ap); - return 0; -} - -int -PluginContext::HeapAlloc(unsigned int cells, cell_t *local_addr, cell_t **phys_addr) -{ - cell_t *addr; - ucell_t realmem; - -#if 0 - if (cells > CELLBOUNDMAX) - { - return SP_ERROR_ARAM; - } -#else - assert(cells < CELLBOUNDMAX); -#endif - - realmem = cells * sizeof(cell_t); - - /** - * Check if the space between the heap and stack is sufficient. - */ - if ((cell_t)(sp_ - hp_ - realmem) < STACKMARGIN) - return SP_ERROR_HEAPLOW; - - addr = (cell_t *)(memory_ + hp_); - /* store size of allocation in cells */ - *addr = (cell_t)cells; - addr++; - hp_ += sizeof(cell_t); - - *local_addr = hp_; - - if (phys_addr) - *phys_addr = addr; - - hp_ += realmem; - - return SP_ERROR_NONE; -} - -int -PluginContext::HeapPop(cell_t local_addr) -{ - cell_t cellcount; - cell_t *addr; - - /* check the bounds of this address */ - local_addr -= sizeof(cell_t); - if (local_addr < (cell_t)data_size_ || local_addr >= sp_) - return SP_ERROR_INVALID_ADDRESS; - - addr = (cell_t *)(memory_ + local_addr); - cellcount = (*addr) * sizeof(cell_t); - /* check if this memory count looks valid */ - if ((signed)(hp_ - cellcount - sizeof(cell_t)) != local_addr) - return SP_ERROR_INVALID_ADDRESS; - - hp_ = local_addr; - - return SP_ERROR_NONE; -} - - -int -PluginContext::HeapRelease(cell_t local_addr) -{ - if (local_addr < (cell_t)data_size_) - return SP_ERROR_INVALID_ADDRESS; - - hp_ = local_addr - sizeof(cell_t); - - return SP_ERROR_NONE; -} - -int -PluginContext::FindNativeByName(const char *name, uint32_t *index) -{ - return m_pRuntime->FindNativeByName(name, index); -} - -int -PluginContext::GetNativeByIndex(uint32_t index, sp_native_t **native) -{ - return m_pRuntime->GetNativeByIndex(index, native); -} - -uint32_t -PluginContext::GetNativesNum() -{ - return m_pRuntime->GetNativesNum(); -} - -int -PluginContext::FindPublicByName(const char *name, uint32_t *index) -{ - return m_pRuntime->FindPublicByName(name, index); -} - -int -PluginContext::GetPublicByIndex(uint32_t index, sp_public_t **pblic) -{ - return m_pRuntime->GetPublicByIndex(index, pblic); -} - -uint32_t -PluginContext::GetPublicsNum() -{ - return m_pRuntime->GetPublicsNum(); -} - -int -PluginContext::GetPubvarByIndex(uint32_t index, sp_pubvar_t **pubvar) -{ - return m_pRuntime->GetPubvarByIndex(index, pubvar); -} - -int -PluginContext::FindPubvarByName(const char *name, uint32_t *index) -{ - return m_pRuntime->FindPubvarByName(name, index); -} - -int -PluginContext::GetPubvarAddrs(uint32_t index, cell_t *local_addr, cell_t **phys_addr) -{ - return m_pRuntime->GetPubvarAddrs(index, local_addr, phys_addr); -} - -uint32_t -PluginContext::GetPubVarsNum() -{ - return m_pRuntime->GetPubVarsNum(); -} - -int -PluginContext::BindNatives(const sp_nativeinfo_t *natives, unsigned int num, int overwrite) -{ - return SP_ERROR_ABORTED; -} - -int -PluginContext::BindNative(const sp_nativeinfo_t *native) -{ - return SP_ERROR_ABORTED; -} - -int -PluginContext::BindNativeToIndex(uint32_t index, SPVM_NATIVE_FUNC func) -{ - return SP_ERROR_ABORTED; -} - -int -PluginContext::BindNativeToAny(SPVM_NATIVE_FUNC native) -{ - return SP_ERROR_ABORTED; -} - -int -PluginContext::LocalToPhysAddr(cell_t local_addr, cell_t **phys_addr) -{ - if (((local_addr >= hp_) && (local_addr < sp_)) || - (local_addr < 0) || ((ucell_t)local_addr >= mem_size_)) - { - return SP_ERROR_INVALID_ADDRESS; - } - - if (phys_addr) - *phys_addr = (cell_t *)(memory_ + local_addr); - - return SP_ERROR_NONE; -} - -int -PluginContext::PushCell(cell_t value) -{ - return SP_ERROR_ABORTED; -} - -int -PluginContext::PushCellsFromArray(cell_t array[], unsigned int numcells) -{ - return SP_ERROR_ABORTED; -} - -int -PluginContext::PushCellArray(cell_t *local_addr, cell_t **phys_addr, cell_t array[], unsigned int numcells) -{ - return SP_ERROR_ABORTED; -} - -int -PluginContext::LocalToString(cell_t local_addr, char **addr) -{ - if (((local_addr >= hp_) && (local_addr < sp_)) || - (local_addr < 0) || ((ucell_t)local_addr >= mem_size_)) - { - return SP_ERROR_INVALID_ADDRESS; - } - *addr = (char *)(memory_ + local_addr); - - return SP_ERROR_NONE; -} - -int -PluginContext::PushString(cell_t *local_addr, char **phys_addr, const char *string) -{ - return SP_ERROR_ABORTED; -} - -int -PluginContext::StringToLocal(cell_t local_addr, size_t bytes, const char *source) -{ - char *dest; - size_t len; - - if (((local_addr >= hp_) && (local_addr < sp_)) || - (local_addr < 0) || ((ucell_t)local_addr >= mem_size_)) - { - return SP_ERROR_INVALID_ADDRESS; - } - - if (bytes == 0) - return SP_ERROR_NONE; - - len = strlen(source); - dest = (char *)(memory_ + local_addr); - - if (len >= bytes) - len = bytes - 1; - - memmove(dest, source, len); - dest[len] = '\0'; - - return SP_ERROR_NONE; -} - -static inline int -__CheckValidChar(char *c) -{ - int count; - int bytecount = 0; - - for (count=1; (*c & 0xC0) == 0x80; count++) - c--; - - switch (*c & 0xF0) - { - case 0xC0: - case 0xD0: - { - bytecount = 2; - break; - } - case 0xE0: - { - bytecount = 3; - break; - } - case 0xF0: - { - bytecount = 4; - break; - } - } - - if (bytecount != count) - return count; - - return 0; -} - -int -PluginContext::StringToLocalUTF8(cell_t local_addr, size_t maxbytes, const char *source, size_t *wrtnbytes) -{ - char *dest; - size_t len; - bool needtocheck = false; - - if (((local_addr >= hp_) && (local_addr < sp_)) || - (local_addr < 0) || - ((ucell_t)local_addr >= mem_size_)) - { - return SP_ERROR_INVALID_ADDRESS; - } - - if (maxbytes == 0) - return SP_ERROR_NONE; - - len = strlen(source); - dest = (char *)(memory_ + local_addr); - - if ((size_t)len >= maxbytes) { - len = maxbytes - 1; - needtocheck = true; - } - - memmove(dest, source, len); - if ((dest[len-1] & 1<<7) && needtocheck) - len -= __CheckValidChar(dest+len-1); - dest[len] = '\0'; - - if (wrtnbytes) - *wrtnbytes = len; - - return SP_ERROR_NONE; -} - -IPluginFunction * -PluginContext::GetFunctionById(funcid_t func_id) -{ - return m_pRuntime->GetFunctionById(func_id); -} - -IPluginFunction * -PluginContext::GetFunctionByName(const char *public_name) -{ - return m_pRuntime->GetFunctionByName(public_name); -} - -int -PluginContext::LocalToStringNULL(cell_t local_addr, char **addr) -{ - int err; - if ((err = LocalToString(local_addr, addr)) != SP_ERROR_NONE) - return err; - - if ((cell_t *)*addr == m_pNullString) - *addr = NULL; - - return SP_ERROR_NONE; -} - -SourceMod::IdentityToken_t * -PluginContext::GetIdentity() -{ - SourceMod::IdentityToken_t *tok; - - if (GetKey(1, (void **)&tok)) - return tok; - return NULL; -} - -cell_t * -PluginContext::GetNullRef(SP_NULL_TYPE type) -{ - if (type == SP_NULL_VECTOR) - return m_pNullVec; - - return NULL; -} - -bool -PluginContext::IsInExec() -{ - for (InvokeFrame *ivk = env_->top(); ivk; ivk = ivk->prev()) { - if (ivk->cx() == this) - return true; - } - return false; -} - -int -PluginContext::Execute2(IPluginFunction *function, const cell_t *params, unsigned int num_params, cell_t *result) -{ - ReportErrorNumber(SP_ERROR_ABORTED); - return SP_ERROR_ABORTED; -} - -bool -PluginContext::Invoke(funcid_t fnid, const cell_t *params, unsigned int num_params, cell_t *result) -{ - EnterProfileScope profileScope("SourcePawn", "EnterJIT"); - - if (!env_->watchdog()->HandleInterrupt()) { - ReportErrorNumber(SP_ERROR_TIMEOUT); - return false; - } - - assert((fnid & 1) != 0); - - unsigned public_id = fnid >> 1; - ScriptedInvoker *cfun = m_pRuntime->GetPublicFunction(public_id); - if (!cfun) { - ReportErrorNumber(SP_ERROR_NOT_FOUND); - return false; - } - - if (m_pRuntime->IsPaused()) { - ReportErrorNumber(SP_ERROR_NOT_RUNNABLE); - return false; - } - - if ((cell_t)(hp_ + 16*sizeof(cell_t)) > (cell_t)(sp_ - (sizeof(cell_t) * (num_params + 1)))) { - ReportErrorNumber(SP_ERROR_STACKLOW); - return false; - } - - // Yuck. We have to do this for compatibility, otherwise something like - // ForwardSys or any sort of multi-callback-fire code would die. Later, - // we'll expose an Invoke() or something that doesn't do this. - env_->clearPendingException(); - - cell_t ignore_result; - if (result == NULL) - result = &ignore_result; - - /* We got this far. It's time to start profiling. */ - EnterProfileScope scriptScope("SourcePawn", cfun->FullName()); - - /* See if we have to compile the callee. */ - CompiledFunction *fn = nullptr; - if (env_->IsJitEnabled()) { - /* We might not have to - check pcode offset. */ - if ((fn = cfun->cachedCompiledFunction()) == nullptr) { - fn = m_pRuntime->GetJittedFunctionByOffset(cfun->Public()->code_offs); - if (!fn) { - int err = SP_ERROR_NONE; - if ((fn = CompileFunction(m_pRuntime, cfun->Public()->code_offs, &err)) == NULL) { - ReportErrorNumber(err); - return false; - } - } - cfun->setCachedCompiledFunction(fn); - } - } else { - ReportError("JIT is not enabled!"); - return false; - } - - /* Save our previous state. */ - cell_t save_sp = sp_; - cell_t save_hp = hp_; - - /* Push parameters */ - sp_ -= sizeof(cell_t) * (num_params + 1); - cell_t *sp = (cell_t *)(memory_ + sp_); - - sp[0] = num_params; - for (unsigned int i = 0; i < num_params; i++) - sp[i + 1] = params[i]; - - // Enter the execution engine. - int ir; - { - InvokeFrame ivkframe(this, fn->GetCodeOffset()); - Environment *env = env_; - ir = env->Invoke(m_pRuntime, fn, result); - } - - if (ir == SP_ERROR_NONE) { - // Verify that our state is still sane. - if (sp_ != save_sp) { - env_->ReportErrorFmt( - SP_ERROR_STACKLEAK, - "Stack leak detected: sp:%d should be %d!", - sp_, - save_sp); - return false; - } - if (hp_ != save_hp) { - env_->ReportErrorFmt( - SP_ERROR_HEAPLEAK, - "Heap leak detected: hp:%d should be %d!", - hp_, - save_hp); - return false; - } - } - - sp_ = save_sp; - hp_ = save_hp; - return ir == SP_ERROR_NONE; -} - -IPluginRuntime * -PluginContext::GetRuntime() -{ - return m_pRuntime; -} - -int -PluginContext::GetLastNativeError() -{ - Environment *env = env_; - if (!env->hasPendingException()) - return SP_ERROR_NONE; - return env->getPendingExceptionCode(); -} - -cell_t * -PluginContext::GetLocalParams() -{ - return (cell_t *)(memory_ + frm_ + (2 * sizeof(cell_t))); -} - -void -PluginContext::SetKey(int k, void *value) -{ - if (k < 1 || k > 4) - return; - - m_keys[k - 1] = value; - m_keys_set[k - 1] = true; -} - -bool -PluginContext::GetKey(int k, void **value) -{ - if (k < 1 || k > 4 || m_keys_set[k - 1] == false) - return false; - - *value = m_keys[k - 1]; - return true; -} - -void -PluginContext::ClearLastNativeError() -{ - if (env_->hasPendingException()) - env_->clearPendingException(); -} - -int -PluginContext::popTrackerAndSetHeap() -{ - assert(tracker_.pCur > tracker_.pBase); - - tracker_.pCur--; - if (tracker_.pCur < tracker_.pBase) - return SP_ERROR_TRACKER_BOUNDS; - - ucell_t amt = *tracker_.pCur; - if (amt > (hp_ - data_size_)) - return SP_ERROR_HEAPMIN; - - hp_ -= amt; - return SP_ERROR_NONE; -} - -int -PluginContext::pushTracker(uint32_t amount) -{ - if ((size_t)(tracker_.pCur - tracker_.pBase) >= tracker_.size) - return SP_ERROR_TRACKER_BOUNDS; - - if (tracker_.pCur + 1 - (tracker_.pBase + tracker_.size) == 0) { - size_t disp = tracker_.size - 1; - tracker_.size *= 2; - tracker_.pBase = (ucell_t *)realloc(tracker_.pBase, tracker_.size * sizeof(cell_t)); - - if (!tracker_.pBase) - return SP_ERROR_TRACKER_BOUNDS; - - tracker_.pCur = tracker_.pBase + disp; - } - - *tracker_.pCur++ = amount; - return SP_ERROR_NONE; -} - -cell_t -PluginContext::invokeNative(ucell_t native_idx, cell_t *params) -{ - cell_t save_sp = sp_; - cell_t save_hp = hp_; - - const sp_native_t *native = m_pRuntime->GetNative(native_idx); - - if (native->status == SP_NATIVE_UNBOUND) { - ReportErrorNumber(SP_ERROR_INVALID_NATIVE); - return 0; - } - - cell_t result = native->pfn(this, params); - - if (save_sp != sp_) { - if (!env_->hasPendingException()) - ReportErrorNumber(SP_ERROR_STACKLEAK); - return 0; - } - if (save_hp != hp_) { - if (!env_->hasPendingException()) - ReportErrorNumber(SP_ERROR_HEAPLEAK); - return 0; - } - - return result; -} - -cell_t -PluginContext::invokeBoundNative(SPVM_NATIVE_FUNC pfn, cell_t *params) -{ - cell_t save_sp = sp_; - cell_t save_hp = hp_; - - cell_t result = pfn(this, params); - - if (save_sp != sp_) { - if (!env_->hasPendingException()) - ReportErrorNumber(SP_ERROR_STACKLEAK); - return result; - } - if (save_hp != hp_) { - if (!env_->hasPendingException()) - ReportErrorNumber(SP_ERROR_HEAPLEAK); - return result; - } - - return result; -} - -struct array_creation_t -{ - const cell_t *dim_list; /* Dimension sizes */ - cell_t dim_count; /* Number of dimensions */ - cell_t *data_offs; /* Current offset AFTER the indirection vectors (data) */ - cell_t *base; /* array base */ -}; - -static cell_t -GenerateInnerArrayIndirectionVectors(array_creation_t *ar, int dim, cell_t cur_offs) -{ - cell_t write_offs = cur_offs; - cell_t *data_offs = ar->data_offs; - - cur_offs += ar->dim_list[dim]; - - // Dimension n-x where x > 2 will have sub-vectors. - // Otherwise, we just need to reference the data section. - if (ar->dim_count > 2 && dim < ar->dim_count - 2) { - // For each index at this dimension, write offstes to our sub-vectors. - // After we write one sub-vector, we generate its sub-vectors recursively. - // At the end, we're given the next offset we can use. - for (int i = 0; i < ar->dim_list[dim]; i++) { - ar->base[write_offs] = (cur_offs - write_offs) * sizeof(cell_t); - write_offs++; - cur_offs = GenerateInnerArrayIndirectionVectors(ar, dim + 1, cur_offs); - } - } else { - // In this section, there are no sub-vectors, we need to write offsets - // to the data. This is separate so the data stays in one big chunk. - // The data offset will increment by the size of the last dimension, - // because that is where the data is finally computed as. - for (int i = 0; i < ar->dim_list[dim]; i++) { - ar->base[write_offs] = (*data_offs - write_offs) * sizeof(cell_t); - write_offs++; - *data_offs = *data_offs + ar->dim_list[dim + 1]; - } - } - - return cur_offs; -} - -static cell_t -calc_indirection(const array_creation_t *ar, cell_t dim) -{ - cell_t size = ar->dim_list[dim]; - if (dim < ar->dim_count - 2) - size += ar->dim_list[dim] * calc_indirection(ar, dim + 1); - return size; -} - -static cell_t -GenerateArrayIndirectionVectors(cell_t *arraybase, cell_t dims[], cell_t _dimcount, bool autozero) -{ - array_creation_t ar; - cell_t data_offs; - - /* Reverse the dimensions */ - cell_t dim_list[sDIMEN_MAX]; - int cur_dim = 0; - for (int i = _dimcount - 1; i >= 0; i--) - dim_list[cur_dim++] = dims[i]; - - ar.base = arraybase; - ar.dim_list = dim_list; - ar.dim_count = _dimcount; - ar.data_offs = &data_offs; - - data_offs = calc_indirection(&ar, 0); - GenerateInnerArrayIndirectionVectors(&ar, 0, 0); - return data_offs; -} - -int -PluginContext::generateFullArray(uint32_t argc, cell_t *argv, int autozero) -{ - // Calculate how many cells are needed. - if (argv[0] <= 0) - return SP_ERROR_ARRAY_TOO_BIG; - - uint32_t cells = argv[0]; - - for (uint32_t dim = 1; dim < argc; dim++) { - cell_t dimsize = argv[dim]; - if (dimsize <= 0) - return SP_ERROR_ARRAY_TOO_BIG; - if (!ke::IsUint32MultiplySafe(cells, dimsize)) - return SP_ERROR_ARRAY_TOO_BIG; - cells *= uint32_t(dimsize); - if (!ke::IsUint32AddSafe(cells, dimsize)) - return SP_ERROR_ARRAY_TOO_BIG; - cells += uint32_t(dimsize); - } - - if (!ke::IsUint32MultiplySafe(cells, 4)) - return SP_ERROR_ARRAY_TOO_BIG; - - uint32_t bytes = cells * 4; - if (!ke::IsUint32AddSafe(hp_, bytes)) - return SP_ERROR_ARRAY_TOO_BIG; - - uint32_t new_hp = hp_ + bytes; - cell_t *dat_hp = reinterpret_cast(memory_ + new_hp); - - // argv, coincidentally, is STK. - if (dat_hp >= argv - STACK_MARGIN) - return SP_ERROR_HEAPLOW; - - if (int err = pushTracker(bytes)) - return err; - - cell_t *base = reinterpret_cast(memory_ + hp_); - cell_t offs = GenerateArrayIndirectionVectors(base, argv, argc, !!autozero); - assert(size_t(offs) == cells); - - argv[argc - 1] = hp_; - hp_ = new_hp; - return SP_ERROR_NONE; -} - -int -PluginContext::generateArray(cell_t dims, cell_t *stk, bool autozero) -{ - if (dims == 1) { - uint32_t size = *stk; - if (size == 0 || !ke::IsUint32MultiplySafe(size, 4)) - return SP_ERROR_ARRAY_TOO_BIG; - *stk = hp_; - - uint32_t bytes = size * 4; - - hp_ += bytes; - if (uintptr_t(memory_ + hp_) >= uintptr_t(stk)) - return SP_ERROR_HEAPLOW; - - if (int err = pushTracker(bytes)) - return err; - - if (autozero) - memset(memory_ + hp_, 0, bytes); - - return SP_ERROR_NONE; - } - - if (int err = generateFullArray(dims, stk, autozero)) - return err; - - return SP_ERROR_NONE; -} - -ISourcePawnEngine2 * -PluginContext::APIv2() -{ - return env_->APIv2(); -} - -void -PluginContext::ReportError(const char *fmt, ...) -{ - va_list ap; - va_start(ap, fmt); - env_->ReportErrorVA(fmt, ap); - va_end(ap); -} - -void -PluginContext::ReportErrorVA(const char *fmt, va_list ap) -{ - env_->ReportErrorVA(fmt, ap); -} - -void -PluginContext::ReportFatalError(const char *fmt, ...) -{ - va_list ap; - va_start(ap, fmt); - env_->ReportErrorVA(SP_ERROR_FATAL, fmt, ap); - va_end(ap); -} - -void -PluginContext::ReportFatalErrorVA(const char *fmt, va_list ap) -{ - env_->ReportErrorVA(SP_ERROR_FATAL, fmt, ap); -} - -void -PluginContext::ReportErrorNumber(int error) -{ - env_->ReportError(error); -} diff --git a/sourcepawn/vm/plugin-context.h b/sourcepawn/vm/plugin-context.h deleted file mode 100644 index 99517f81..00000000 --- a/sourcepawn/vm/plugin-context.h +++ /dev/null @@ -1,193 +0,0 @@ -// vim: set sts=2 ts=8 sw=2 tw=99 et: -// -// Copyright (C) 2006-2015 AlliedModders LLC -// -// This file is part of SourcePawn. SourcePawn is free software: you can -// redistribute it and/or modify it under the terms of the GNU General Public -// License as published by the Free Software Foundation, either version 3 of -// the License, or (at your option) any later version. -// -// You should have received a copy of the GNU General Public License along with -// SourcePawn. If not, see http://www.gnu.org/licenses/. -// -#ifndef _INCLUDE_SOURCEPAWN_BASECONTEXT_H_ -#define _INCLUDE_SOURCEPAWN_BASECONTEXT_H_ - -#include "sp_vm_api.h" -#include "scripted-invoker.h" -#include "plugin-runtime.h" - -namespace sp { - -struct HeapTracker -{ - HeapTracker() - : size(0), - pBase(nullptr), - pCur(nullptr) - {} - size_t size; - ucell_t *pBase; - ucell_t *pCur; -}; - -static const size_t SP_MAX_RETURN_STACK = 1024; - -class Environment; -class PluginContext; - -class PluginContext : public IPluginContext -{ - public: - PluginContext(PluginRuntime *pRuntime); - ~PluginContext(); - - bool Initialize(); - - public: //IPluginContext - IVirtualMachine *GetVirtualMachine(); - sp_context_t *GetContext(); - bool IsDebugging(); - int SetDebugBreak(void *newpfn, void *oldpfn); - IPluginDebugInfo *GetDebugInfo(); - int HeapAlloc(unsigned int cells, cell_t *local_addr, cell_t **phys_addr); - int HeapPop(cell_t local_addr); - int HeapRelease(cell_t local_addr); - int FindNativeByName(const char *name, uint32_t *index); - int GetNativeByIndex(uint32_t index, sp_native_t **native); - uint32_t GetNativesNum(); - int FindPublicByName(const char *name, uint32_t *index); - int GetPublicByIndex(uint32_t index, sp_public_t **publicptr); - uint32_t GetPublicsNum(); - int GetPubvarByIndex(uint32_t index, sp_pubvar_t **pubvar); - int FindPubvarByName(const char *name, uint32_t *index); - int GetPubvarAddrs(uint32_t index, cell_t *local_addr, cell_t **phys_addr); - uint32_t GetPubVarsNum(); - int LocalToPhysAddr(cell_t local_addr, cell_t **phys_addr); - int LocalToString(cell_t local_addr, char **addr); - int StringToLocal(cell_t local_addr, size_t chars, const char *source); - int StringToLocalUTF8(cell_t local_addr, size_t maxbytes, const char *source, size_t *wrtnbytes); - int PushCell(cell_t value); - int PushCellArray(cell_t *local_addr, cell_t **phys_addr, cell_t array[], unsigned int numcells); - int PushString(cell_t *local_addr, char **phys_addr, const char *string); - int PushCellsFromArray(cell_t array[], unsigned int numcells); - int BindNatives(const sp_nativeinfo_t *natives, unsigned int num, int overwrite); - int BindNative(const sp_nativeinfo_t *native); - int BindNativeToAny(SPVM_NATIVE_FUNC native); - int Execute(uint32_t code_addr, cell_t *result); - cell_t ThrowNativeErrorEx(int error, const char *msg, ...); - cell_t ThrowNativeError(const char *msg, ...); - IPluginFunction *GetFunctionByName(const char *public_name); - IPluginFunction *GetFunctionById(funcid_t func_id); - SourceMod::IdentityToken_t *GetIdentity(); - cell_t *GetNullRef(SP_NULL_TYPE type); - int LocalToStringNULL(cell_t local_addr, char **addr); - int BindNativeToIndex(uint32_t index, SPVM_NATIVE_FUNC native); - int Execute2(IPluginFunction *function, const cell_t *params, unsigned int num_params, cell_t *result); - IPluginRuntime *GetRuntime(); - int GetLastNativeError(); - cell_t *GetLocalParams(); - void SetKey(int k, void *value); - bool GetKey(int k, void **value); - void Refresh(); - void ClearLastNativeError(); - ISourcePawnEngine2 *APIv2() KE_OVERRIDE; - void ReportError(const char *fmt, ...) KE_OVERRIDE; - void ReportErrorVA(const char *fmt, va_list ap) KE_OVERRIDE; - void ReportFatalError(const char *fmt, ...) KE_OVERRIDE; - void ReportFatalErrorVA(const char *fmt, va_list ap) KE_OVERRIDE; - void ReportErrorNumber(int error) KE_OVERRIDE; - - bool Invoke(funcid_t fnid, const cell_t *params, unsigned int num_params, cell_t *result); - - size_t HeapSize() const { - return mem_size_; - } - uint8_t *memory() const { - return memory_; - } - size_t DataSize() const { - return data_size_; - } - PluginRuntime *runtime() const { - return m_pRuntime; - } - - public: - bool IsInExec(); - - static inline size_t offsetOfTracker() { - return offsetof(PluginContext, tracker_); - } - static inline size_t offsetOfSp() { - return offsetof(PluginContext, sp_); - } - static inline size_t offsetOfRuntime() { - return offsetof(PluginContext, m_pRuntime); - } - static inline size_t offsetOfMemory() { - return offsetof(PluginContext, memory_); - } - - int32_t *addressOfSp() { - return &sp_; - } - cell_t *addressOfFrm() { - return &frm_; - } - cell_t *addressOfHp() { - return &hp_; - } - - cell_t frm() const { - return frm_; - } - cell_t hp() const { - return hp_; - } - - int popTrackerAndSetHeap(); - int pushTracker(uint32_t amount); - - int generateArray(cell_t dims, cell_t *stk, bool autozero); - int generateFullArray(uint32_t argc, cell_t *argv, int autozero); - cell_t invokeNative(ucell_t native_idx, cell_t *params); - cell_t invokeBoundNative(SPVM_NATIVE_FUNC pfn, cell_t *params); - - inline bool checkAddress(cell_t *stk, cell_t addr) { - if (uint32_t(addr) >= mem_size_) - return false; - - if (addr < hp_) - return true; - - if (reinterpret_cast(memory_ + addr) < stk) - return false; - - return true; - } - - private: - Environment *env_; - PluginRuntime *m_pRuntime; - uint8_t *memory_; - uint32_t data_size_; - uint32_t mem_size_; - - cell_t *m_pNullVec; - cell_t *m_pNullString; - void *m_keys[4]; - bool m_keys_set[4]; - - // Tracker for local HEA growth. - HeapTracker tracker_; - - // Stack, heap, and frame pointer. - cell_t sp_; - cell_t hp_; - cell_t frm_; -}; - -} // namespace sp - -#endif //_INCLUDE_SOURCEPAWN_BASECONTEXT_H_ diff --git a/sourcepawn/vm/plugin-runtime.cpp b/sourcepawn/vm/plugin-runtime.cpp deleted file mode 100644 index 7a700e77..00000000 --- a/sourcepawn/vm/plugin-runtime.cpp +++ /dev/null @@ -1,494 +0,0 @@ -// vim: set sts=2 ts=8 sw=2 tw=99 et: -// -// Copyright (C) 2006-2015 AlliedModders LLC -// -// This file is part of SourcePawn. SourcePawn is free software: you can -// redistribute it and/or modify it under the terms of the GNU General Public -// License as published by the Free Software Foundation, either version 3 of -// the License, or (at your option) any later version. -// -// You should have received a copy of the GNU General Public License along with -// SourcePawn. If not, see http://www.gnu.org/licenses/. -// -#include -#include -#include -#include -#include "plugin-runtime.h" -#include "x86/jit_x86.h" -#include "plugin-context.h" -#include "environment.h" - -#include "md5/md5.h" - -using namespace sp; -using namespace SourcePawn; - -static inline bool -IsPointerCellAligned(void *p) -{ - return uintptr_t(p) % 4 == 0; -} - -PluginRuntime::PluginRuntime(LegacyImage *image) - : image_(image), - paused_(false), - computed_code_hash_(false), - computed_data_hash_(false) -{ - code_ = image_->DescribeCode(); - data_ = image_->DescribeData(); - memset(code_hash_, 0, sizeof(code_hash_)); - memset(data_hash_, 0, sizeof(data_hash_)); - - ke::AutoLock lock(Environment::get()->lock()); - Environment::get()->RegisterRuntime(this); -} - -PluginRuntime::~PluginRuntime() -{ - // The watchdog thread takes the global JIT lock while it patches all - // runtimes. It is not enough to ensure that the unlinking of the runtime is - // protected; we cannot delete functions or code while the watchdog might be - // executing. Therefore, the entire destructor is guarded. - ke::AutoLock lock(Environment::get()->lock()); - - Environment::get()->DeregisterRuntime(this); - - for (uint32_t i = 0; i < image_->NumPublics(); i++) - delete entrypoints_[i]; - - for (size_t i = 0; i < m_JitFunctions.length(); i++) - delete m_JitFunctions[i]; -} - -bool -PluginRuntime::Initialize() -{ - if (!ke::IsAligned(code_.bytes, sizeof(cell_t))) { - // Align the code section. - aligned_code_ = new uint8_t[code_.length]; - if (!aligned_code_) - return false; - - memcpy(aligned_code_, code_.bytes, code_.length); - code_.bytes = aligned_code_; - } - - natives_ = new sp_native_t[image_->NumNatives()]; - if (!natives_) - return false; - memset(natives_, 0, sizeof(sp_native_t) * image_->NumNatives()); - - publics_ = new sp_public_t[image_->NumPublics()]; - if (!publics_) - return false; - memset(publics_, 0, sizeof(sp_public_t) * image_->NumPublics()); - - pubvars_ = new sp_pubvar_t[image_->NumPubvars()]; - if (!pubvars_) - return false; - memset(pubvars_, 0, sizeof(sp_pubvar_t) * image_->NumPubvars()); - - entrypoints_ = new ScriptedInvoker *[image_->NumPublics()]; - if (!entrypoints_) - return false; - memset(entrypoints_, 0, sizeof(ScriptedInvoker *) * image_->NumPublics()); - - context_ = new PluginContext(this); - if (!context_->Initialize()) - return false; - - SetupFloatNativeRemapping(); - - if (!function_map_.init(32)) - return false; - - return true; -} - -struct NativeMapping { - const char *name; - unsigned opcode; -}; - -static const NativeMapping sNativeMap[] = { - { "FloatAbs", OP_FABS }, - { "FloatAdd", OP_FLOATADD }, - { "FloatSub", OP_FLOATSUB }, - { "FloatMul", OP_FLOATMUL }, - { "FloatDiv", OP_FLOATDIV }, - { "float", OP_FLOAT }, - { "FloatCompare", OP_FLOATCMP }, - { "RoundToCeil", OP_RND_TO_CEIL }, - { "RoundToZero", OP_RND_TO_ZERO }, - { "RoundToFloor", OP_RND_TO_FLOOR }, - { "RoundToNearest", OP_RND_TO_NEAREST }, - { "__FLOAT_GT__", OP_FLOAT_GT }, - { "__FLOAT_GE__", OP_FLOAT_GE }, - { "__FLOAT_LT__", OP_FLOAT_LT }, - { "__FLOAT_LE__", OP_FLOAT_LE }, - { "__FLOAT_EQ__", OP_FLOAT_EQ }, - { "__FLOAT_NE__", OP_FLOAT_NE }, - { "__FLOAT_NOT__", OP_FLOAT_NOT }, - { NULL, 0 }, -}; - -void -PluginRuntime::SetupFloatNativeRemapping() -{ - float_table_ = new floattbl_t[image_->NumNatives()]; - for (size_t i = 0; i < image_->NumNatives(); i++) { - const char *name = image_->GetNative(i); - const NativeMapping *iter = sNativeMap; - while (iter->name) { - if (strcmp(name, iter->name) == 0) { - float_table_[i].found = true; - float_table_[i].index = iter->opcode; - break; - } - iter++; - } - } -} - -unsigned -PluginRuntime::GetNativeReplacement(size_t index) -{ - if (!float_table_[index].found) - return OP_NOP; - return float_table_[index].index; -} - -void -PluginRuntime::SetNames(const char *fullname, const char *name) -{ - name_ = name; - full_name_ = name; -} - -static cell_t -InvalidNative(IPluginContext *pCtx, const cell_t *params) -{ - return pCtx->ThrowNativeErrorEx(SP_ERROR_INVALID_NATIVE, "Invalid native"); -} - -void -PluginRuntime::AddJittedFunction(CompiledFunction *fn) -{ - m_JitFunctions.append(fn); - - ucell_t pcode_offset = fn->GetCodeOffset(); - { - FunctionMap::Insert p = function_map_.findForAdd(pcode_offset); - assert(!p.found()); - - function_map_.add(p, pcode_offset, fn); - } -} - -CompiledFunction * -PluginRuntime::GetJittedFunctionByOffset(cell_t pcode_offset) -{ - FunctionMap::Result r = function_map_.find(pcode_offset); - if (!r.found()) - return nullptr; - return r->value; -} - -int -PluginRuntime::FindNativeByName(const char *name, uint32_t *index) -{ - size_t idx; - if (!image_->FindNative(name, &idx)) - return SP_ERROR_NOT_FOUND; - - if (index) - *index = idx; - - return SP_ERROR_NONE; -} - -int -PluginRuntime::GetNativeByIndex(uint32_t index, sp_native_t **native) -{ - return SP_ERROR_PARAM; -} - -int -PluginRuntime::UpdateNativeBinding(uint32_t index, SPVM_NATIVE_FUNC pfn, uint32_t flags, void *data) -{ - if (index >= image_->NumNatives()) - return SP_ERROR_INDEX; - - sp_native_t *native = &natives_[index]; - - native->pfn = pfn; - native->status = pfn - ? SP_NATIVE_BOUND - : SP_NATIVE_UNBOUND; - native->flags = flags; - native->user = data; - return SP_ERROR_NONE; -} - -const sp_native_t * -PluginRuntime::GetNative(uint32_t index) -{ - if (index >= image_->NumNatives()) - return nullptr; - - if (!natives_[index].name) - natives_[index].name = image_->GetNative(index); - - return &natives_[index]; -} - -uint32_t -PluginRuntime::GetNativesNum() -{ - return image_->NumNatives(); -} - -int -PluginRuntime::FindPublicByName(const char *name, uint32_t *index) -{ - size_t idx; - if (!image_->FindPublic(name, &idx)) - return SP_ERROR_NOT_FOUND; - - if (index) - *index = idx; - return SP_ERROR_NONE; -} - -int -PluginRuntime::GetPublicByIndex(uint32_t index, sp_public_t **out) -{ - if (index >= image_->NumPublics()) - return SP_ERROR_INDEX; - - sp_public_t &entry = publics_[index]; - if (!entry.name) { - uint32_t offset; - image_->GetPublic(index, &offset, &entry.name); - entry.code_offs = offset; - entry.funcid = (index << 1) | 1; - } - - if (out) - *out = &entry; - return SP_ERROR_NONE; -} - -uint32_t -PluginRuntime::GetPublicsNum() -{ - return image_->NumPublics(); -} - -int -PluginRuntime::GetPubvarByIndex(uint32_t index, sp_pubvar_t **out) -{ - if (index >= image_->NumPubvars()) - return SP_ERROR_INDEX; - - sp_pubvar_t *pubvar = &pubvars_[index]; - if (!pubvar->name) { - uint32_t offset; - image_->GetPubvar(index, &offset, &pubvar->name); - if (int err = context_->LocalToPhysAddr(offset, &pubvar->offs)) - return err; - } - - if (out) - *out = pubvar; - return SP_ERROR_NONE; -} - -int -PluginRuntime::FindPubvarByName(const char *name, uint32_t *index) -{ - size_t idx; - if (!image_->FindPubvar(name, &idx)) - return SP_ERROR_NOT_FOUND; - - if (index) - *index = idx; - return SP_ERROR_NONE; -} - -int -PluginRuntime::GetPubvarAddrs(uint32_t index, cell_t *local_addr, cell_t **phys_addr) -{ - if (index >= image_->NumPubvars()) - return SP_ERROR_INDEX; - - uint32_t offset; - image_->GetPubvar(index, &offset, nullptr); - - if (int err = context_->LocalToPhysAddr(offset, phys_addr)) - return err; - *local_addr = offset; - return SP_ERROR_NONE; -} - -uint32_t -PluginRuntime::GetPubVarsNum() -{ - return image_->NumPubvars(); -} - -IPluginContext * -PluginRuntime::GetDefaultContext() -{ - return context_; -} - -IPluginDebugInfo * -PluginRuntime::GetDebugInfo() -{ - return this; -} - -IPluginFunction * -PluginRuntime::GetFunctionById(funcid_t func_id) -{ - ScriptedInvoker *pFunc = NULL; - - if (func_id & 1) { - func_id >>= 1; - if (func_id >= image_->NumPublics()) - return NULL; - pFunc = entrypoints_[func_id]; - if (!pFunc) { - entrypoints_[func_id] = new ScriptedInvoker(this, (func_id << 1) | 1, func_id); - pFunc = entrypoints_[func_id]; - } - } - - return pFunc; -} - -ScriptedInvoker * -PluginRuntime::GetPublicFunction(size_t index) -{ - assert(index < image_->NumPublics()); - ScriptedInvoker *pFunc = entrypoints_[index]; - if (!pFunc) { - sp_public_t *pub = NULL; - GetPublicByIndex(index, &pub); - if (pub) - entrypoints_[index] = new ScriptedInvoker(this, (index << 1) | 1, index); - pFunc = entrypoints_[index]; - } - - return pFunc; -} - -IPluginFunction * -PluginRuntime::GetFunctionByName(const char *public_name) -{ - uint32_t index; - - if (FindPublicByName(public_name, &index) != SP_ERROR_NONE) - return NULL; - - return GetPublicFunction(index); -} - -bool -PluginRuntime::IsDebugging() -{ - return true; -} - -void -PluginRuntime::SetPauseState(bool paused) -{ - paused_ = paused; -} - -bool -PluginRuntime::IsPaused() -{ - return paused_; -} - -size_t -PluginRuntime::GetMemUsage() -{ - return sizeof(*this) + - sizeof(PluginContext) + - image_->ImageSize() + - (aligned_code_ ? code_.length : 0) + - context_->HeapSize(); -} - -unsigned char * -PluginRuntime::GetCodeHash() -{ - if (!computed_code_hash_) { - MD5 md5_pcode; - md5_pcode.update((const unsigned char *)code_.bytes, code_.length); - md5_pcode.finalize(); - md5_pcode.raw_digest(code_hash_); - computed_code_hash_ = true; - } - return code_hash_; -} - -unsigned char * -PluginRuntime::GetDataHash() -{ - if (!computed_data_hash_) { - MD5 md5_data; - md5_data.update((const unsigned char *)data_.bytes, data_.length); - md5_data.finalize(); - md5_data.raw_digest(data_hash_); - computed_data_hash_ = true; - } - return data_hash_; -} - -PluginContext * -PluginRuntime::GetBaseContext() -{ - return context_; -} - -int -PluginRuntime::ApplyCompilationOptions(ICompilation *co) -{ - return SP_ERROR_NONE; -} - -int -PluginRuntime::LookupLine(ucell_t addr, uint32_t *line) -{ - if (!image_->LookupLine(addr, line)) - return SP_ERROR_NOT_FOUND; - return SP_ERROR_NONE; -} - -int -PluginRuntime::LookupFunction(ucell_t addr, const char **out) -{ - const char *name = image_->LookupFunction(addr); - if (!name) - return SP_ERROR_NOT_FOUND; - if (out) - *out = name; - return SP_ERROR_NONE; -} - -int -PluginRuntime::LookupFile(ucell_t addr, const char **out) -{ - const char *name = image_->LookupFile(addr); - if (!name) - return SP_ERROR_NOT_FOUND; - if (out) - *out = name; - return SP_ERROR_NONE; -} diff --git a/sourcepawn/vm/plugin-runtime.h b/sourcepawn/vm/plugin-runtime.h deleted file mode 100644 index 0412b675..00000000 --- a/sourcepawn/vm/plugin-runtime.h +++ /dev/null @@ -1,156 +0,0 @@ -// vim: set sts=2 ts=8 sw=2 tw=99 et: -// -// Copyright (C) 2006-2015 AlliedModders LLC -// -// This file is part of SourcePawn. SourcePawn is free software: you can -// redistribute it and/or modify it under the terms of the GNU General Public -// License as published by the Free Software Foundation, either version 3 of -// the License, or (at your option) any later version. -// -// You should have received a copy of the GNU General Public License along with -// SourcePawn. If not, see http://www.gnu.org/licenses/. -// -#ifndef _INCLUDE_SOURCEPAWN_JIT_RUNTIME_H_ -#define _INCLUDE_SOURCEPAWN_JIT_RUNTIME_H_ - -#include -#include -#include -#include -#include -#include "compiled-function.h" -#include "scripted-invoker.h" -#include "legacy-image.h" - -namespace sp { - -class PluginContext; - -struct floattbl_t -{ - floattbl_t() { - found = false; - index = 0; - } - bool found; - unsigned int index; -}; - -/* Jit wants fast access to this so we expose things as public */ -class PluginRuntime - : public SourcePawn::IPluginRuntime, - public SourcePawn::IPluginDebugInfo, - public ke::InlineListNode -{ - public: - PluginRuntime(LegacyImage *image); - ~PluginRuntime(); - - bool Initialize(); - - public: - virtual bool IsDebugging(); - virtual IPluginDebugInfo *GetDebugInfo(); - virtual int FindNativeByName(const char *name, uint32_t *index); - virtual int GetNativeByIndex(uint32_t index, sp_native_t **native); - virtual uint32_t GetNativesNum(); - virtual int FindPublicByName(const char *name, uint32_t *index); - virtual int GetPublicByIndex(uint32_t index, sp_public_t **publicptr); - virtual uint32_t GetPublicsNum(); - virtual int GetPubvarByIndex(uint32_t index, sp_pubvar_t **pubvar); - virtual int FindPubvarByName(const char *name, uint32_t *index); - virtual int GetPubvarAddrs(uint32_t index, cell_t *local_addr, cell_t **phys_addr); - virtual uint32_t GetPubVarsNum(); - virtual IPluginFunction *GetFunctionByName(const char *public_name); - virtual IPluginFunction *GetFunctionById(funcid_t func_id); - virtual IPluginContext *GetDefaultContext(); - virtual int ApplyCompilationOptions(ICompilation *co); - virtual void SetPauseState(bool paused); - virtual bool IsPaused(); - virtual size_t GetMemUsage(); - virtual unsigned char *GetCodeHash(); - virtual unsigned char *GetDataHash(); - CompiledFunction *GetJittedFunctionByOffset(cell_t pcode_offset); - void AddJittedFunction(CompiledFunction *fn); - void SetNames(const char *fullname, const char *name); - unsigned GetNativeReplacement(size_t index); - ScriptedInvoker *GetPublicFunction(size_t index); - int UpdateNativeBinding(uint32_t index, SPVM_NATIVE_FUNC pfn, uint32_t flags, void *data) KE_OVERRIDE; - const sp_native_t *GetNative(uint32_t index) KE_OVERRIDE; - int LookupLine(ucell_t addr, uint32_t *line) KE_OVERRIDE; - int LookupFunction(ucell_t addr, const char **name) KE_OVERRIDE; - int LookupFile(ucell_t addr, const char **filename) KE_OVERRIDE; - const char *GetFilename() KE_OVERRIDE { - return full_name_.chars(); - } - - PluginContext *GetBaseContext(); - - size_t NumJitFunctions() const { - return m_JitFunctions.length(); - } - CompiledFunction *GetJitFunction(size_t i) const { - return m_JitFunctions[i]; - } - const char *Name() const { - return name_.chars(); - } - - public: - typedef LegacyImage::Code Code; - typedef LegacyImage::Data Data; - - const Code &code() const { - return code_; - } - const Data &data() const { - return data_; - } - LegacyImage *image() const { - return image_; - } - - private: - void SetupFloatNativeRemapping(); - - private: - ke::AutoPtr image_; - ke::AutoArray aligned_code_; - ke::AutoArray float_table_; - ke::AString name_; - ke::AString full_name_; - Code code_; - Data data_; - ke::AutoArray natives_; - ke::AutoArray publics_; - ke::AutoArray pubvars_; - ke::AutoArray entrypoints_; - ke::AutoPtr context_; - - struct FunctionMapPolicy { - static inline uint32_t hash(ucell_t value) { - return ke::HashInteger<4>(value); - } - static inline bool matches(ucell_t a, ucell_t b) { - return a == b; - } - }; - typedef ke::HashMap FunctionMap; - - FunctionMap function_map_; - ke::Vector m_JitFunctions; - - // Pause state. - bool paused_; - - // Checksumming. - bool computed_code_hash_; - bool computed_data_hash_; - unsigned char code_hash_[16]; - unsigned char data_hash_[16]; -}; - -} // sp - -#endif //_INCLUDE_SOURCEPAWN_JIT_RUNTIME_H_ - diff --git a/sourcepawn/vm/scripted-invoker.cpp b/sourcepawn/vm/scripted-invoker.cpp deleted file mode 100644 index c6acd2d7..00000000 --- a/sourcepawn/vm/scripted-invoker.cpp +++ /dev/null @@ -1,354 +0,0 @@ -// vim: set sts=2 ts=8 sw=2 tw=99 et: -// -// Copyright (C) 2006-2015 AlliedModders LLC -// -// This file is part of SourcePawn. SourcePawn is free software: you can -// redistribute it and/or modify it under the terms of the GNU General Public -// License as published by the Free Software Foundation, either version 3 of -// the License, or (at your option) any later version. -// -// You should have received a copy of the GNU General Public License along with -// SourcePawn. If not, see http://www.gnu.org/licenses/. -// - -#include -#include -#include "scripted-invoker.h" -#include "plugin-runtime.h" -#include "environment.h" -#include "plugin-context.h" - -/******************** -* FUNCTION CALLING * -********************/ - -using namespace sp; -using namespace SourcePawn; - -ScriptedInvoker::ScriptedInvoker(PluginRuntime *runtime, funcid_t id, uint32_t pub_id) - : env_(Environment::get()), - context_(runtime->GetBaseContext()), - m_curparam(0), - m_errorstate(SP_ERROR_NONE), - m_FnId(id), - cc_function_(nullptr) -{ - runtime->GetPublicByIndex(pub_id, &public_); - - size_t rt_len = strlen(runtime->Name()); - size_t len = rt_len + strlen("::") + strlen(public_->name); - - full_name_ = new char[len + 1]; - strcpy(full_name_, runtime->Name()); - strcpy(&full_name_[rt_len], "::"); - strcpy(&full_name_[rt_len + 2], public_->name); -} - -ScriptedInvoker::~ScriptedInvoker() -{ -} - -bool -ScriptedInvoker::IsRunnable() -{ - return !context_->runtime()->IsPaused(); -} - -int -ScriptedInvoker::CallFunction(const cell_t *params, unsigned int num_params, cell_t *result) -{ - Environment::get()->ReportError(SP_ERROR_ABORTED); - return SP_ERROR_ABORTED; -} - -int -ScriptedInvoker::CallFunction2(IPluginContext *pContext, const cell_t *params, unsigned int num_params, cell_t *result) -{ - Environment::get()->ReportError(SP_ERROR_ABORTED); - return SP_ERROR_ABORTED; -} - -IPluginContext * -ScriptedInvoker::GetParentContext() -{ - return context_; -} - -int ScriptedInvoker::PushCell(cell_t cell) -{ - if (m_curparam >= SP_MAX_EXEC_PARAMS) - return SetError(SP_ERROR_PARAMS_MAX); - - m_info[m_curparam].marked = false; - m_params[m_curparam] = cell; - m_curparam++; - - return SP_ERROR_NONE; -} - -int -ScriptedInvoker::PushCellByRef(cell_t *cell, int flags) -{ - return PushArray(cell, 1, flags); -} - -int -ScriptedInvoker::PushFloat(float number) -{ - cell_t val = *(cell_t *)&number; - - return PushCell(val); -} - -int -ScriptedInvoker::PushFloatByRef(float *number, int flags) -{ - return PushCellByRef((cell_t *)number, flags); -} - -int -ScriptedInvoker::PushArray(cell_t *inarray, unsigned int cells, int copyback) -{ - if (m_curparam >= SP_MAX_EXEC_PARAMS) - { - return SetError(SP_ERROR_PARAMS_MAX); - } - - ParamInfo *info = &m_info[m_curparam]; - - info->flags = inarray ? copyback : 0; - info->marked = true; - info->size = cells; - info->str.is_sz = false; - info->orig_addr = inarray; - - m_curparam++; - - return SP_ERROR_NONE; -} - -int -ScriptedInvoker::PushString(const char *string) -{ - return _PushString(string, SM_PARAM_STRING_COPY, 0, strlen(string)+1); -} - -int -ScriptedInvoker::PushStringEx(char *buffer, size_t length, int sz_flags, int cp_flags) -{ - return _PushString(buffer, sz_flags, cp_flags, length); -} - -int -ScriptedInvoker::_PushString(const char *string, int sz_flags, int cp_flags, size_t len) -{ - if (m_curparam >= SP_MAX_EXEC_PARAMS) - return SetError(SP_ERROR_PARAMS_MAX); - - ParamInfo *info = &m_info[m_curparam]; - - info->marked = true; - info->orig_addr = (cell_t *)string; - info->flags = cp_flags; - info->size = len; - info->str.sz_flags = sz_flags; - info->str.is_sz = true; - - m_curparam++; - - return SP_ERROR_NONE; -} - -void -ScriptedInvoker::Cancel() -{ - if (!m_curparam) - return; - - m_errorstate = SP_ERROR_NONE; - m_curparam = 0; -} - -int -ScriptedInvoker::Execute(cell_t *result) -{ - Environment *env = Environment::get(); - env->clearPendingException(); - - // For backward compatibility, we have to clear the exception state. - // Otherwise code like this: - // - // static cell_t native(cx, params) { - // for (auto callback : callbacks) { - // callback->Execute(); - // } - // } - // - // Could unintentionally leak a pending exception back to the caller, - // which wouldn't have happened before the Great Exception Refactoring. - ExceptionHandler eh(context_); - if (!Invoke(result)) { - assert(env->hasPendingException()); - return env->getPendingExceptionCode(); - } - - return SP_ERROR_NONE; -} - -bool -ScriptedInvoker::Invoke(cell_t *result) -{ - if (!IsRunnable()) { - Cancel(); - env_->ReportError(SP_ERROR_NOT_RUNNABLE); - return false; - } - if (int err = m_errorstate) { - Cancel(); - env_->ReportError(err); - return false; - } - - //This is for re-entrancy! - cell_t temp_params[SP_MAX_EXEC_PARAMS]; - ParamInfo temp_info[SP_MAX_EXEC_PARAMS]; - unsigned int numparams = m_curparam; - unsigned int i; - - if (numparams) - { - //Save the info locally, then reset it for re-entrant calls. - memcpy(temp_info, m_info, numparams * sizeof(ParamInfo)); - } - m_curparam = 0; - - /* Browse the parameters and build arrays */ - bool ok = true; - for (i=0; iHeapAlloc( - temp_info[i].size, - &(temp_info[i].local_addr), - &(temp_info[i].phys_addr)); - if (err != SP_ERROR_NONE) { - env_->ReportError(err); - ok = false; - break; - } - if (temp_info[i].orig_addr) - { - memcpy(temp_info[i].phys_addr, temp_info[i].orig_addr, sizeof(cell_t) * temp_info[i].size); - } - } else { - /* Calculate cells required for the string */ - size_t cells = (temp_info[i].size + sizeof(cell_t) - 1) / sizeof(cell_t); - - /* Allocate the buffer */ - int err = context_->HeapAlloc( - cells, - &(temp_info[i].local_addr), - &(temp_info[i].phys_addr)); - if (err != SP_ERROR_NONE) { - env_->ReportError(err); - ok = false; - break; - } - - /* Copy original string if necessary */ - if ((temp_info[i].str.sz_flags & SM_PARAM_STRING_COPY) && (temp_info[i].orig_addr != NULL)) - { - /* Cut off UTF-8 properly */ - if (temp_info[i].str.sz_flags & SM_PARAM_STRING_UTF8) { - context_->StringToLocalUTF8( - temp_info[i].local_addr, - temp_info[i].size, - (const char *)temp_info[i].orig_addr, - NULL); - } - /* Copy a binary blob */ - else if (temp_info[i].str.sz_flags & SM_PARAM_STRING_BINARY) - { - memmove(temp_info[i].phys_addr, temp_info[i].orig_addr, temp_info[i].size); - } - /* Copy ASCII characters */ - else - { - context_->StringToLocal( - temp_info[i].local_addr, - temp_info[i].size, - (const char *)temp_info[i].orig_addr); - } - } - } /* End array/string calculation */ - /* Update the pushed parameter with the byref local address */ - temp_params[i] = temp_info[i].local_addr; - } else { - /* Just copy the value normally */ - temp_params[i] = m_params[i]; - } - } - - /* Make the call if we can */ - if (ok) - ok = context_->Invoke(m_FnId, temp_params, numparams, result); - - /* i should be equal to the last valid parameter + 1 */ - bool docopies = ok; - while (i--) { - if (!temp_info[i].marked) - continue; - - if (docopies && (temp_info[i].flags & SM_PARAM_COPYBACK)) { - if (temp_info[i].orig_addr) { - if (temp_info[i].str.is_sz) { - memcpy(temp_info[i].orig_addr, temp_info[i].phys_addr, temp_info[i].size); - - } else { - if (temp_info[i].size == 1) { - *temp_info[i].orig_addr = *(temp_info[i].phys_addr); - } else { - memcpy(temp_info[i].orig_addr, - temp_info[i].phys_addr, - temp_info[i].size * sizeof(cell_t)); - } - } - } - } - - if (int err = context_->HeapPop(temp_info[i].local_addr)) - env_->ReportError(err); - } - - return !env_->hasPendingException(); -} - -int -ScriptedInvoker::Execute2(IPluginContext *ctx, cell_t *result) -{ - Environment::get()->ReportError(SP_ERROR_ABORTED); - return SP_ERROR_ABORTED; -} - -IPluginRuntime * -ScriptedInvoker::GetParentRuntime() -{ - return context_->runtime(); -} - -funcid_t -ScriptedInvoker::GetFunctionID() -{ - return m_FnId; -} - -int -ScriptedInvoker::SetError(int err) -{ - m_errorstate = err; - - return err; -} - diff --git a/sourcepawn/vm/scripted-invoker.h b/sourcepawn/vm/scripted-invoker.h deleted file mode 100644 index b9911da3..00000000 --- a/sourcepawn/vm/scripted-invoker.h +++ /dev/null @@ -1,104 +0,0 @@ -// vim: set sts=2 ts=8 sw=2 tw=99 et: -// -// Copyright (C) 2006-2015 AlliedModders LLC -// -// This file is part of SourcePawn. SourcePawn is free software: you can -// redistribute it and/or modify it under the terms of the GNU General Public -// License as published by the Free Software Foundation, either version 3 of -// the License, or (at your option) any later version. -// -// You should have received a copy of the GNU General Public License along with -// SourcePawn. If not, see http://www.gnu.org/licenses/. -// -#ifndef _INCLUDE_SOURCEMOD_BASEFUNCTION_H_ -#define _INCLUDE_SOURCEMOD_BASEFUNCTION_H_ - -#include -#include - -namespace sp { - -using namespace SourcePawn; - -class PluginRuntime; -class PluginContext; -class CompiledFunction; - -struct ParamInfo -{ - int flags; /* Copy-back flags */ - bool marked; /* Whether this is marked as being used */ - cell_t local_addr; /* Local address to free */ - cell_t *phys_addr; /* Physical address of our copy */ - cell_t *orig_addr; /* Original address to copy back to */ - ucell_t size; /* Size of array in bytes */ - struct { - bool is_sz; /* is a string */ - int sz_flags; /* has sz flags */ - } str; -}; - -class ScriptedInvoker : public IPluginFunction -{ - public: - ScriptedInvoker(PluginRuntime *pRuntime, funcid_t fnid, uint32_t pub_id); - ~ScriptedInvoker(); - - public: - int PushCell(cell_t cell); - int PushCellByRef(cell_t *cell, int flags); - int PushFloat(float number); - int PushFloatByRef(float *number, int flags); - int PushArray(cell_t *inarray, unsigned int cells, int copyback); - int PushString(const char *string); - int PushStringEx(char *buffer, size_t length, int sz_flags, int cp_flags); - int Execute(cell_t *result); - void Cancel(); - int CallFunction(const cell_t *params, unsigned int num_params, cell_t *result); - IPluginContext *GetParentContext(); - bool Invoke(cell_t *result); - bool IsRunnable(); - funcid_t GetFunctionID(); - int Execute2(IPluginContext *ctx, cell_t *result); - int CallFunction2(IPluginContext *ctx, - const cell_t *params, - unsigned int num_params, - cell_t *result); - IPluginRuntime *GetParentRuntime(); - - public: - const char *FullName() const { - return full_name_; - } - sp_public_t *Public() const { - return public_; - } - - CompiledFunction *cachedCompiledFunction() const { - return cc_function_; - } - void setCachedCompiledFunction(CompiledFunction *fn) { - cc_function_ = fn; - } - - private: - int _PushString(const char *string, int sz_flags, int cp_flags, size_t len); - int SetError(int err); - - private: - Environment *env_; - PluginRuntime *m_pRuntime; - PluginContext *context_; - cell_t m_params[SP_MAX_EXEC_PARAMS]; - ParamInfo m_info[SP_MAX_EXEC_PARAMS]; - unsigned int m_curparam; - int m_errorstate; - funcid_t m_FnId; - ke::AutoArray full_name_; - sp_public_t *public_; - CompiledFunction *cc_function_; -}; - -} // namespace sp - -#endif //_INCLUDE_SOURCEMOD_BASEFUNCTION_H_ diff --git a/sourcepawn/vm/smx-v1-image.cpp b/sourcepawn/vm/smx-v1-image.cpp deleted file mode 100644 index 261a77b1..00000000 --- a/sourcepawn/vm/smx-v1-image.cpp +++ /dev/null @@ -1,617 +0,0 @@ -// vim: set sts=2 ts=8 sw=2 tw=99 et: -// -// Copyright (C) 2004-2015 AlliedModers LLC -// -// This file is part of SourcePawn. SourcePawn is licensed under the GNU -// General Public License, version 3.0 (GPL). If a copy of the GPL was not -// provided with this file, you can obtain it here: -// http://www.gnu.org/licenses/gpl.html -// -#include "smx-v1-image.h" -#include "zlib/zlib.h" - -using namespace ke; -using namespace sp; - -SmxV1Image::SmxV1Image(FILE *fp) - : FileReader(fp), - hdr_(nullptr), - header_strings_(nullptr), - names_section_(nullptr), - names_(nullptr), - debug_names_section_(nullptr), - debug_names_(nullptr), - debug_syms_(nullptr), - debug_syms_unpacked_(nullptr) -{ -} - -// Validating SMX v1 scripts is fairly expensive. We reserve real validation -// for v2. -bool -SmxV1Image::validate() -{ - if (length_ < sizeof(sp_file_hdr_t)) - return error("bad header"); - - hdr_ = (sp_file_hdr_t *)buffer(); - if (hdr_->magic != SmxConsts::FILE_MAGIC) - return error("bad header"); - - switch (hdr_->version) { - case SmxConsts::SP1_VERSION_1_0: - case SmxConsts::SP1_VERSION_1_1: - case SmxConsts::SP1_VERSION_1_7: - break; - default: - return error("unsupported version"); - } - - switch (hdr_->compression) { - case SmxConsts::FILE_COMPRESSION_GZ: - { - // The start of the compression cannot be larger than the file. - if (hdr_->dataoffs > length_) - return error("illegal compressed region"); - - // The compressed region must start after the header. - if (hdr_->dataoffs < sizeof(sp_file_hdr_t)) - return error("illegal compressed region"); - - // The full size of the image must be at least as large as the start - // of the compressed region. - if (hdr_->imagesize < hdr_->dataoffs) - return error("illegal image size"); - - // Allocate the uncompressed image buffer. - uint32_t compressedSize = hdr_->disksize - hdr_->dataoffs; - AutoArray uncompressed(new uint8_t[hdr_->imagesize]); - if (!uncompressed) - return error("out of memory"); - - // Decompress. - const uint8_t *src = buffer() + hdr_->dataoffs; - uint8_t *dest = (uint8_t *)uncompressed + hdr_->dataoffs; - uLongf destlen = hdr_->imagesize - hdr_->dataoffs; - int rv = uncompress( - (Bytef *)dest, - &destlen, - src, - compressedSize); - if (rv != Z_OK) - return error("could not decode compressed region"); - - // Copy the initial uncompressed region back in. - memcpy((uint8_t *)uncompressed, buffer(), hdr_->dataoffs); - - // Replace the original buffer. - length_ = hdr_->imagesize; - buffer_ = uncompressed.take(); - hdr_ = (sp_file_hdr_t *)buffer(); - break; - } - - case SmxConsts::FILE_COMPRESSION_NONE: - break; - - default: - return error("unknown compression type"); - } - - // Validate the string table. - if (hdr_->stringtab >= length_) - return error("invalid string table"); - header_strings_ = reinterpret_cast(buffer() + hdr_->stringtab); - - // Validate sections header. - if ((sizeof(sp_file_hdr_t) + hdr_->sections * sizeof(sp_file_section_t)) > length_) - return error("invalid section table"); - - size_t last_header_string = 0; - const sp_file_section_t *sections = - reinterpret_cast(buffer() + sizeof(sp_file_hdr_t)); - for (size_t i = 0; i < hdr_->sections; i++) { - if (sections[i].nameoffs >= (hdr_->dataoffs - hdr_->stringtab)) - return error("invalid section name"); - - if (sections[i].nameoffs > last_header_string) - last_header_string = sections[i].nameoffs; - - sections_.append(Section()); - sections_.back().dataoffs = sections[i].dataoffs; - sections_.back().size = sections[i].size; - sections_.back().name = header_strings_ + sections[i].nameoffs; - } - - // Validate sanity of section header strings. - bool found_terminator = false; - for (const uint8_t *iter = buffer() + last_header_string; - iter < buffer() + hdr_->dataoffs; - iter++) - { - if (*iter == '\0') { - found_terminator = true; - break; - } - } - if (!found_terminator) - return error("malformed section names header"); - - names_section_ = findSection(".names"); - if (!names_section_) - return error("could not find .names section"); - if (!validateSection(names_section_)) - return error("invalid names section"); - names_ = reinterpret_cast(buffer() + names_section_->dataoffs); - - // The names section must be 0-length or be null-terminated. - if (names_section_->size != 0 && - *(names_ + names_section_->size - 1) != '\0') - { - return error("malformed names section"); - } - - if (!validateCode()) - return false; - if (!validateData()) - return false; - if (!validatePublics()) - return false; - if (!validatePubvars()) - return false; - if (!validateNatives()) - return false; - if (!validateDebugInfo()) - return false; - - return true; -} - -const SmxV1Image::Section * -SmxV1Image::findSection(const char *name) -{ - for (size_t i = 0; i < sections_.length(); i++) { - if (strcmp(sections_[i].name, name) == 0) - return §ions_[i]; - } - return nullptr; -} - -bool -SmxV1Image::validateSection(const Section *section) -{ - if (section->dataoffs >= length_) - return false; - if (section->size > length_ - section->dataoffs) - return false; - return true; -} - -bool -SmxV1Image::validateData() -{ - // .data is required. - const Section *section = findSection(".data"); - if (!section) - return error("could not find data"); - if (!validateSection(section)) - return error("invalid data section"); - - const sp_file_data_t *data = - reinterpret_cast(buffer() + section->dataoffs); - if (data->data > section->size) - return error("invalid data blob"); - if (data->datasize > (section->size - data->data)) - return error("invalid data blob"); - - const uint8_t *blob = - reinterpret_cast(data) + data->data; - data_ = Blob(section, data, blob, data->datasize); - return true; -} - -bool -SmxV1Image::validateCode() -{ - // .code is required. - const Section *section = findSection(".code"); - if (!section) - return error("could not find code"); - if (!validateSection(section)) - return error("invalid code section"); - - const sp_file_code_t *code = - reinterpret_cast(buffer() + section->dataoffs); - if (code->codeversion < SmxConsts::CODE_VERSION_SP1_MIN) - return error("code version is too old, no longer supported"); - if (code->codeversion > SmxConsts::CODE_VERSION_SP1_MAX) - return error("code version is too new, not supported"); - if (code->cellsize != 4) - return error("unsupported cellsize"); - if (code->flags & ~CODEFLAG_DEBUG) - return error("unsupported code settings"); - if (code->code > section->size) - return error("invalid code blob"); - if (code->codesize > (section->size - code->code)) - return error("invalid code blob"); - - const uint8_t *blob = - reinterpret_cast(code) + code->code; - code_ = Blob(section, code, blob, code->codesize); - return true; -} - -bool -SmxV1Image::validatePublics() -{ - const Section *section = findSection(".publics"); - if (!section) - return true; - if (!validateSection(section)) - return error("invalid .publics section"); - if ((section->size % sizeof(sp_file_publics_t)) != 0) - return error("invalid .publics section"); - - const sp_file_publics_t *publics = - reinterpret_cast(buffer() + section->dataoffs); - size_t length = section->size / sizeof(sp_file_publics_t); - - for (size_t i = 0; i < length; i++) { - if (!validateName(publics[i].name)) - return error("invalid public name"); - } - - publics_ = List(publics, length); - return true; -} - -bool -SmxV1Image::validatePubvars() -{ - const Section *section = findSection(".pubvars"); - if (!section) - return true; - if (!validateSection(section)) - return error("invalid .pubvars section"); - if ((section->size % sizeof(sp_file_pubvars_t)) != 0) - return error("invalid .pubvars section"); - - const sp_file_pubvars_t *pubvars = - reinterpret_cast(buffer() + section->dataoffs); - size_t length = section->size / sizeof(sp_file_pubvars_t); - - for (size_t i = 0; i < length; i++) { - if (!validateName(pubvars[i].name)) - return error("invalid pubvar name"); - } - - pubvars_ = List(pubvars, length); - return true; -} - -bool -SmxV1Image::validateNatives() -{ - const Section *section = findSection(".natives"); - if (!section) - return true; - if (!validateSection(section)) - return error("invalid .natives section"); - if ((section->size % sizeof(sp_file_natives_t)) != 0) - return error("invalid .natives section"); - - const sp_file_natives_t *natives = - reinterpret_cast(buffer() + section->dataoffs); - size_t length = section->size / sizeof(sp_file_natives_t); - - for (size_t i = 0; i < length; i++) { - if (!validateName(natives[i].name)) - return error("invalid pubvar name"); - } - - natives_ = List(natives, length); - return true; -} - -bool -SmxV1Image::validateName(size_t offset) -{ - return offset < names_section_->size; -} - -bool -SmxV1Image::validateDebugInfo() -{ - const Section *dbginfo = findSection(".dbg.info"); - if (!dbginfo) - return true; - if (!validateSection(dbginfo)) - return error("invalid .dbg.info section"); - - debug_info_ = - reinterpret_cast(buffer() + dbginfo->dataoffs); - - debug_names_section_ = findSection(".dbg.strings"); - if (!debug_names_section_) - return error("no debug string table"); - if (!validateSection(debug_names_section_)) - return error("invalid .dbg.strings section"); - debug_names_ = reinterpret_cast(buffer() + debug_names_section_->dataoffs); - - // Name tables must be null-terminated. - if (debug_names_section_->size != 0 && - *(debug_names_ + debug_names_section_->size - 1) != '\0') - { - return error("invalid .dbg.strings section"); - } - - const Section *files = findSection(".dbg.files"); - if (!files) - return error("no debug file table"); - if (!validateSection(files)) - return error("invalid debug file table"); - if (files->size < sizeof(sp_fdbg_file_t) * debug_info_->num_files) - return error("invalid debug file table"); - debug_files_ = List( - reinterpret_cast(buffer() + files->dataoffs), - debug_info_->num_files); - - const Section *lines = findSection(".dbg.lines"); - if (!lines) - return error("no debug lines table"); - if (!validateSection(lines)) - return error("invalid debug lines table"); - if (lines->size < sizeof(sp_fdbg_line_t) * debug_info_->num_lines) - return error("invalid debug lines table"); - debug_lines_ = List( - reinterpret_cast(buffer() + lines->dataoffs), - debug_info_->num_lines); - - debug_symbols_section_ = findSection(".dbg.symbols"); - if (!debug_symbols_section_) - return error("no debug symbol table"); - if (!validateSection(debug_symbols_section_)) - return error("invalid debug symbol table"); - - // See the note about unpacked debug sections in smx-headers.h. - if (hdr_->version == SmxConsts::SP1_VERSION_1_0 && - !findSection(".dbg.natives")) - { - debug_syms_unpacked_ = - reinterpret_cast(buffer() + debug_symbols_section_->dataoffs); - } else { - debug_syms_ = - reinterpret_cast(buffer() + debug_symbols_section_->dataoffs); - } - - return true; -} - -auto -SmxV1Image::DescribeCode() const -> Code -{ - Code code; - code.bytes = code_.blob(); - code.length = code_.length(); - switch (code_->codeversion) { - case SmxConsts::CODE_VERSION_JIT_1_0: - code.version = CodeVersion::SP_1_0; - break; - case SmxConsts::CODE_VERSION_JIT_1_1: - code.version = CodeVersion::SP_1_1; - break; - default: - assert(false); - code.version = CodeVersion::Unknown; - break; - } - return code; -} - -auto -SmxV1Image::DescribeData() const -> Data -{ - Data data; - data.bytes = data_.blob(); - data.length = data_.length(); - return data; -} - -size_t -SmxV1Image::NumNatives() const -{ - return natives_.length(); -} - -const char * -SmxV1Image::GetNative(size_t index) const -{ - assert(index < natives_.length()); - return names_ + natives_[index].name; -} - -bool -SmxV1Image::FindNative(const char *name, size_t *indexp) const -{ - for (size_t i = 0; i < natives_.length(); i++) { - const char *candidate = names_ + natives_[i].name; - if (strcmp(candidate, name) == 0) { - if (indexp) - *indexp = i; - return true; - } - } - return false; -} - -size_t -SmxV1Image::NumPublics() const -{ - return publics_.length(); -} - -void -SmxV1Image::GetPublic(size_t index, uint32_t *offsetp, const char **namep) const -{ - assert(index < publics_.length()); - if (offsetp) - *offsetp = publics_[index].address; - if (namep) - *namep = names_ + publics_[index].name; -} - -bool -SmxV1Image::FindPublic(const char *name, size_t *indexp) const -{ - int high = publics_.length() - 1; - int low = 0; - while (low <= high) { - int mid = (low + high) / 2; - const char *candidate = names_ + publics_[mid].name; - int diff = strcmp(candidate, name); - if (diff == 0) { - if (indexp) { - *indexp = mid; - return true; - } - } - if (diff < 0) - low = mid + 1; - else - high = mid - 1; - } - return false; -} - -size_t -SmxV1Image::NumPubvars() const -{ - return pubvars_.length(); -} - -void -SmxV1Image::GetPubvar(size_t index, uint32_t *offsetp, const char **namep) const -{ - assert(index < pubvars_.length()); - if (offsetp) - *offsetp = pubvars_[index].address; - if (namep) - *namep = names_ + pubvars_[index].name; -} - -bool -SmxV1Image::FindPubvar(const char *name, size_t *indexp) const -{ - int high = pubvars_.length() - 1; - int low = 0; - while (low <= high) { - int mid = (low + high) / 2; - const char *candidate = names_ + pubvars_[mid].name; - int diff = strcmp(candidate, name); - if (diff == 0) { - if (indexp) { - *indexp = mid; - return true; - } - } - if (diff < 0) - low = mid + 1; - else - high = mid - 1; - } - return false; -} - -size_t -SmxV1Image::HeapSize() const -{ - return data_->memsize; -} - -size_t -SmxV1Image::ImageSize() const -{ - return length_; -} - -const char * -SmxV1Image::LookupFile(uint32_t addr) -{ - int high = debug_files_.length(); - int low = -1; - - while (high - low > 1) { - int mid = (low + high) / 2; - if (debug_files_[mid].addr <= addr) - low = mid; - else - high = mid; - } - - if (low == -1) - return nullptr; - if (debug_files_[low].name >= debug_names_section_->size) - return nullptr; - - return debug_names_ + debug_files_[low].name; -} - -template -const char * -SmxV1Image::lookupFunction(const SymbolType *syms, uint32_t addr) -{ - const uint8_t *cursor = reinterpret_cast(syms); - const uint8_t *cursor_end = cursor + debug_symbols_section_->size; - for (uint32_t i = 0; i < debug_info_->num_syms; i++) { - if (cursor + sizeof(SymbolType) > cursor_end) - break; - - const SymbolType *sym = reinterpret_cast(cursor); - if (sym->ident == sp::IDENT_FUNCTION && - sym->codestart <= addr && - sym->codeend > addr) - { - if (sym->name >= debug_names_section_->size) - return nullptr; - return debug_names_ + sym->name; - } - - if (sym->dimcount > 0) - cursor += sizeof(DimType) * sym->dimcount; - cursor += sizeof(SymbolType); - } - return nullptr; -} - -const char * -SmxV1Image::LookupFunction(uint32_t code_offset) -{ - if (debug_syms_) { - return lookupFunction( - debug_syms_, code_offset); - } - return lookupFunction( - debug_syms_unpacked_, code_offset); -} - -bool -SmxV1Image::LookupLine(uint32_t addr, uint32_t *line) -{ - int high = debug_lines_.length(); - int low = -1; - - while (high - low > 1) { - int mid = (low + high) / 2; - if (debug_lines_[mid].addr <= addr) - low = mid; - else - high = mid; - } - - if (low == -1) - return false; - - // Since the CIP occurs BEFORE the line, we have to add one. - *line = debug_lines_[low].line + 1; - return true; -} diff --git a/sourcepawn/vm/smx-v1-image.h b/sourcepawn/vm/smx-v1-image.h deleted file mode 100644 index b98b3b9f..00000000 --- a/sourcepawn/vm/smx-v1-image.h +++ /dev/null @@ -1,204 +0,0 @@ -// vim: set sts=2 ts=8 sw=2 tw=99 et: -// -// Copyright (C) 2004-2015 AlliedModers LLC -// -// This file is part of SourcePawn. SourcePawn is licensed under the GNU -// General Public License, version 3.0 (GPL). If a copy of the GPL was not -// provided with this file, you can obtain it here: -// http://www.gnu.org/licenses/gpl.html -// -#ifndef _include_sourcepawn_smx_parser_h_ -#define _include_sourcepawn_smx_parser_h_ - -#include -#include -#include -#include -#include -#include -#include "file-utils.h" -#include "legacy-image.h" - -namespace sp { - -class SmxV1Image - : public FileReader, - public LegacyImage -{ - public: - SmxV1Image(FILE *fp); - - // This must be called to initialize the reader. - bool validate(); - - const sp_file_hdr_t *hdr() const { - return hdr_; - } - - const char *errorMessage() const { - return error_.chars(); - } - - public: - Code DescribeCode() const KE_OVERRIDE; - Data DescribeData() const KE_OVERRIDE; - size_t NumNatives() const KE_OVERRIDE; - const char *GetNative(size_t index) const KE_OVERRIDE; - bool FindNative(const char *name, size_t *indexp) const KE_OVERRIDE; - size_t NumPublics() const KE_OVERRIDE; - void GetPublic(size_t index, uint32_t *offsetp, const char **namep) const KE_OVERRIDE; - bool FindPublic(const char *name, size_t *indexp) const KE_OVERRIDE; - size_t NumPubvars() const KE_OVERRIDE; - void GetPubvar(size_t index, uint32_t *offsetp, const char **namep) const KE_OVERRIDE; - bool FindPubvar(const char *name, size_t *indexp) const KE_OVERRIDE; - size_t HeapSize() const KE_OVERRIDE; - size_t ImageSize() const KE_OVERRIDE; - const char *LookupFile(uint32_t code_offset) KE_OVERRIDE; - const char *LookupFunction(uint32_t code_offset) KE_OVERRIDE; - bool LookupLine(uint32_t code_offset, uint32_t *line) KE_OVERRIDE; - - private: - struct Section - { - const char *name; - uint32_t dataoffs; - uint32_t size; - }; - const Section *findSection(const char *name); - - public: - template - class Blob - { - public: - Blob() - : header_(nullptr), - section_(nullptr), - blob_(nullptr), - length_(0) - {} - Blob(const Section *header, - const T *section, - const uint8_t *blob, - size_t length) - : header_(header), - section_(section), - blob_(blob), - length_(length) - {} - - size_t size() const { - return section_->size; - } - const T * operator ->() const { - return section_; - } - const uint8_t *blob() const { - return blob_; - } - size_t length() const { - return length_; - } - bool exists() const { - return !!header_; - } - - private: - const Section *header_; - const T *section_; - const uint8_t *blob_; - size_t length_; - }; - - template - class List - { - public: - List() - : section_(nullptr), - length_(0) - {} - List(const T *section, size_t length) - : section_(section), - length_(length) - {} - - size_t length() const { - return length_; - } - const T &operator[](size_t index) const { - assert(index < length()); - return section_[index]; - } - bool exists() const { - return !!section_; - } - - private: - const T *section_; - size_t length_; - }; - - public: - const Blob &code() const { - return code_; - } - const Blob &data() const { - return data_; - } - const List &publics() const { - return publics_; - } - const List &natives() const { - return natives_; - } - const List &pubvars() const { - return pubvars_; - } - - protected: - bool error(const char *msg) { - error_ = msg; - return false; - } - bool validateName(size_t offset); - bool validateSection(const Section *section); - bool validateCode(); - bool validateData(); - bool validatePublics(); - bool validatePubvars(); - bool validateNatives(); - bool validateDebugInfo(); - - private: - template - const char *lookupFunction(const SymbolType *syms, uint32_t addr); - - private: - sp_file_hdr_t *hdr_; - ke::AString error_; - const char *header_strings_; - ke::Vector
sections_; - - const Section *names_section_; - const char *names_; - - Blob code_; - Blob data_; - List publics_; - List natives_; - List pubvars_; - - const Section *debug_names_section_; - const char *debug_names_; - const sp_fdbg_info_t *debug_info_; - List debug_files_; - List debug_lines_; - const Section *debug_symbols_section_; - const sp_fdbg_symbol_t *debug_syms_; - const sp_u_fdbg_symbol_t *debug_syms_unpacked_; -}; - -} // namespace sp - -#endif // _include_sourcepawn_smx_parser_h_ diff --git a/sourcepawn/vm/stack-frames.cpp b/sourcepawn/vm/stack-frames.cpp deleted file mode 100644 index 40206cff..00000000 --- a/sourcepawn/vm/stack-frames.cpp +++ /dev/null @@ -1,227 +0,0 @@ -// vim: set sts=2 ts=8 sw=2 tw=99 et: -// -// Copyright (C) 2006-2015 AlliedModders LLC -// -// This file is part of SourcePawn. SourcePawn is free software: you can -// redistribute it and/or modify it under the terms of the GNU General Public -// License as published by the Free Software Foundation, either version 3 of -// the License, or (at your option) any later version. -// -// You should have received a copy of the GNU General Public License along with -// SourcePawn. If not, see http://www.gnu.org/licenses/. -// -#include "environment.h" -#include "plugin-runtime.h" -#include "plugin-context.h" -#include "stack-frames.h" -#include "x86/frames-x86.h" -#include "compiled-function.h" - -using namespace ke; -using namespace sp; -using namespace SourcePawn; - -InvokeFrame::InvokeFrame(PluginContext *cx, ucell_t entry_cip) - : prev_(Environment::get()->top()), - cx_(cx), - prev_exit_frame_(Environment::get()->exit_frame()), - entry_cip_(0), - entry_sp_(nullptr) -{ - Environment::get()->enterInvoke(this); -} - -InvokeFrame::~InvokeFrame() -{ - assert(Environment::get()->top() == this); - Environment::get()->leaveInvoke(); -} - -FrameIterator::FrameIterator() - : ivk_(Environment::get()->top()), - exit_frame_(Environment::get()->exit_frame()), - runtime_(nullptr), - sp_iter_(nullptr), - sp_stop_(nullptr), - function_cip_(kInvalidCip), - cip_(kInvalidCip), - pc_(nullptr) -{ - if (!ivk_) - return; - - nextInvokeFrame(); -} - -void -FrameIterator::nextInvokeFrame() -{ - assert(exit_frame_.exit_sp()); - sp_iter_ = exit_frame_.exit_sp(); - - // Inside an exit frame, the stack looks like this: - // .. C++ .. - // ----------- <-- entry_sp - // return addr to C++ - // entry cip for frame #0 - // alignment - // ----------- - // return addr to frame #0 - // entry cip for frame #1 - // alignment - // ----------- <-- exit sp - // saved regs - // return addr - // .. InvokeNativeBoundHelper() .. - // - // We are guaranteed to always have one frame. We subtract one frame from - // the entry sp so we hit the stopping point correctly. - assert(ivk_->entry_sp()); - assert(ke::IsAligned(sizeof(JitFrame), sizeof(intptr_t))); - sp_stop_ = ivk_->entry_sp() - (sizeof(JitFrame) / sizeof(intptr_t)); - assert(sp_stop_ >= sp_iter_); - - runtime_ = ivk_->cx()->runtime(); - function_cip_ = kInvalidCip; - pc_ = nullptr; - cip_ = kInvalidCip; - - if (!exit_frame_.has_exit_native()) { - // We have an exit frame, but it's not for natives. automatically advance - // to the most recent scripted frame. - const JitExitFrameForHelper *exit = - JitExitFrameForHelper::FromExitSp(exit_frame_.exit_sp()); - exit_frame_ = ExitFrame(); - - // If we haven't compiled the function yet, but threw an error, then the - // return address will be null. - pc_ = exit->return_address; - assert(pc_ || exit->isCompileFunction()); - - // The function owning pc_ is in the previous frame. - const JitFrame *frame = exit->prev(); - function_cip_ = frame->function_cip; - sp_iter_ = reinterpret_cast(frame); - return; - } -} - -void -FrameIterator::Next() -{ - void *pc = nullptr; - if (exit_frame_.has_exit_native()) { - // If we're at an exit frame, the return address will yield the current pc. - const JitExitFrameForNative *exit = - JitExitFrameForNative::FromExitSp(exit_frame_.exit_sp()); - exit_frame_ = ExitFrame(); - - pc_ = exit->return_address; - cip_ = kInvalidCip; - - // The function owning pc_ is in the previous frame. - const JitFrame *frame = JitFrame::FromSp(sp_iter_); - function_cip_ = frame->function_cip; - return; - } - - if (sp_iter_ >= sp_stop_) { - // Jump to the next invoke frame. - exit_frame_ = ivk_->prev_exit_frame(); - ivk_ = ivk_->prev(); - if (!ivk_) - return; - - nextInvokeFrame(); - return; - } - - pc_ = JitFrame::FromSp(sp_iter_)->return_address; - assert(pc_); - - // Advance, and find the function cip the pc belongs to. - sp_iter_ = reinterpret_cast(JitFrame::FromSp(sp_iter_) + 1); - function_cip_ = JitFrame::FromSp(sp_iter_)->function_cip; - cip_ = kInvalidCip; -} - -void -FrameIterator::Reset() -{ - *this = FrameIterator(); -} - -cell_t -FrameIterator::findCip() const -{ - CompiledFunction *fn = runtime_->GetJittedFunctionByOffset(function_cip_); - if (!fn) - return 0; - - if (cip_ == kInvalidCip) { - if (pc_) - cip_ = fn->FindCipByPc(pc_); - else - cip_ = function_cip_; - } - return cip_; -} - -unsigned -FrameIterator::LineNumber() const -{ - ucell_t cip = findCip(); - if (cip == kInvalidCip) - return 0; - - uint32_t line; - if (!runtime_->image()->LookupLine(cip, &line)) - return 0; - - return line; -} - -const char * -FrameIterator::FilePath() const -{ - ucell_t cip = findCip(); - if (cip == kInvalidCip) - return runtime_->image()->LookupFile(function_cip_); - - return runtime_->image()->LookupFile(cip); -} - -const char * -FrameIterator::FunctionName() const -{ - assert(ivk_); - if (exit_frame_.has_exit_native()) { - uint32_t native_index = exit_frame_.exit_native(); - const sp_native_t *native = runtime_->GetNative(native_index); - if (!native) - return nullptr; - return native->name; - } - - return runtime_->image()->LookupFunction(function_cip_); -} - -bool -FrameIterator::IsNativeFrame() const -{ - return exit_frame_.has_exit_native(); -} - -bool -FrameIterator::IsScriptedFrame() const -{ - return !IsNativeFrame() && ivk_; -} - -IPluginContext * -FrameIterator::Context() const -{ - if (!ivk_) - return nullptr; - return ivk_->cx(); -} diff --git a/sourcepawn/vm/stack-frames.h b/sourcepawn/vm/stack-frames.h deleted file mode 100644 index 2ab3b0da..00000000 --- a/sourcepawn/vm/stack-frames.h +++ /dev/null @@ -1,135 +0,0 @@ -// vim: set sts=2 ts=8 sw=2 tw=99 et: -// -// Copyright (C) 2006-2015 AlliedModders LLC -// -// This file is part of SourcePawn. SourcePawn is free software: you can -// redistribute it and/or modify it under the terms of the GNU General Public -// License as published by the Free Software Foundation, either version 3 of -// the License, or (at your option) any later version. -// -// You should have received a copy of the GNU General Public License along with -// SourcePawn. If not, see http://www.gnu.org/licenses/. -// -#ifndef _include_sourcepawn_vm_stack_frames_h_ -#define _include_sourcepawn_vm_stack_frames_h_ - -#include -#include - -namespace sp { - -using namespace SourcePawn; - -class PluginContext; -class PluginRuntime; - -// An ExitFrame represents the state of the most recent exit from VM state to -// the outside world. Because this transition is on a critical path, we declare -// exactly one ExitFrame and save/restore it in InvokeFrame(). Anytime we're in -// the VM, we are guaranteed to have an ExitFrame for each InvokeFrame(). -class ExitFrame -{ - public: - ExitFrame() - : exit_sp_(nullptr), - exit_native_(-1) - {} - - public: - const intptr_t *exit_sp() const { - return exit_sp_; - } - bool has_exit_native() const { - return exit_native_ != -1; - } - uint32_t exit_native() const { - assert(has_exit_native()); - return exit_native_; - } - - public: - static inline size_t offsetOfExitSp() { - return offsetof(ExitFrame, exit_sp_); - } - static inline size_t offsetOfExitNative() { - return offsetof(ExitFrame, exit_native_); - } - - private: - const intptr_t *exit_sp_; - int exit_native_; -}; - -// An InvokeFrame represents one activation of Execute2(). -class InvokeFrame -{ - public: - InvokeFrame(PluginContext *cx, ucell_t cip); - ~InvokeFrame(); - - InvokeFrame *prev() const { - return prev_; - } - PluginContext *cx() const { - return cx_; - } - - const ExitFrame &prev_exit_frame() const { - return prev_exit_frame_; - } - const intptr_t *entry_sp() const { - return entry_sp_; - } - ucell_t entry_cip() const { - return entry_cip_; - } - - public: - static inline size_t offsetOfEntrySp() { - return offsetof(InvokeFrame, entry_sp_); - } - - private: - InvokeFrame *prev_; - PluginContext *cx_; - ExitFrame prev_exit_frame_; - ucell_t entry_cip_; - const intptr_t *entry_sp_; -}; - -class FrameIterator : public SourcePawn::IFrameIterator -{ - public: - FrameIterator(); - - bool Done() const KE_OVERRIDE { - return !ivk_; - } - void Next() KE_OVERRIDE; - void Reset() KE_OVERRIDE; - - bool IsNativeFrame() const KE_OVERRIDE; - bool IsScriptedFrame() const KE_OVERRIDE; - const char *FunctionName() const KE_OVERRIDE; - const char *FilePath() const KE_OVERRIDE; - unsigned LineNumber() const KE_OVERRIDE; - IPluginContext *Context() const KE_OVERRIDE; - - private: - void nextInvokeFrame(); - cell_t findCip() const; - - private: - InvokeFrame *ivk_; - ExitFrame exit_frame_; - PluginRuntime *runtime_; - const intptr_t *sp_iter_; - const intptr_t *sp_stop_; - ucell_t function_cip_; - mutable ucell_t cip_; - void *pc_; -}; - -} // namespace sp - -#endif // _include_sourcepawn_vm_stack_frames_h_ diff --git a/sourcepawn/vm/version.rc b/sourcepawn/vm/version.rc deleted file mode 100644 index d79b5214..00000000 --- a/sourcepawn/vm/version.rc +++ /dev/null @@ -1,103 +0,0 @@ -// Microsoft Visual C++ generated resource script. -// - -#define APSTUDIO_READONLY_SYMBOLS -///////////////////////////////////////////////////////////////////////////// -// -// Generated from the TEXTINCLUDE 2 resource. -// -#include "winres.h" - -#include - -///////////////////////////////////////////////////////////////////////////// -#undef APSTUDIO_READONLY_SYMBOLS - -///////////////////////////////////////////////////////////////////////////// -// English (U.S.) resources - -#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) -#ifdef _WIN32 -LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US -#pragma code_page(1252) -#endif //_WIN32 - -///////////////////////////////////////////////////////////////////////////// -// -// Version -// - -VS_VERSION_INFO VERSIONINFO - FILEVERSION SM_VERSION_FILE - PRODUCTVERSION SM_VERSION_FILE - FILEFLAGSMASK 0x17L -#ifdef _DEBUG - FILEFLAGS 0x1L -#else - FILEFLAGS 0x0L -#endif - FILEOS 0x4L - FILETYPE 0x2L - FILESUBTYPE 0x0L -BEGIN - BLOCK "StringFileInfo" - BEGIN - BLOCK "000004b0" - BEGIN - VALUE "Comments", "SourcePawn JIT" - VALUE "FileDescription", "SourcePawn JIT/Virtual Machine" - VALUE "FileVersion", SM_VERSION_STRING - VALUE "InternalName", "sourcemod" - VALUE "LegalCopyright", "Copyright (c) 2004-2008, AlliedModders LLC" - VALUE "OriginalFilename", "sourcepawn.jit.x86.dll" - VALUE "ProductName", "SourcePawn JIT" - VALUE "ProductVersion", SM_VERSION_STRING - END - END - BLOCK "VarFileInfo" - BEGIN - VALUE "Translation", 0x0, 1200 - END -END - - -#ifdef APSTUDIO_INVOKED -///////////////////////////////////////////////////////////////////////////// -// -// TEXTINCLUDE -// - -1 TEXTINCLUDE -BEGIN - "resource.h\0" -END - -2 TEXTINCLUDE -BEGIN - "#include ""winres.h""\r\n" - "\0" -END - -3 TEXTINCLUDE -BEGIN - "\r\n" - "\0" -END - -#endif // APSTUDIO_INVOKED - -#endif // English (U.S.) resources -///////////////////////////////////////////////////////////////////////////// - - - -#ifndef APSTUDIO_INVOKED -///////////////////////////////////////////////////////////////////////////// -// -// Generated from the TEXTINCLUDE 3 resource. -// - - -///////////////////////////////////////////////////////////////////////////// -#endif // not APSTUDIO_INVOKED - diff --git a/sourcepawn/vm/watchdog_timer.cpp b/sourcepawn/vm/watchdog_timer.cpp deleted file mode 100644 index 56e8480b..00000000 --- a/sourcepawn/vm/watchdog_timer.cpp +++ /dev/null @@ -1,165 +0,0 @@ -// vim: set ts=8 sts=2 sw=2 tw=99 et: -// -// This file is part of SourcePawn. -// -// SourcePawn is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// SourcePawn is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU General Public License -// along with SourcePawn. If not, see . -#include "watchdog_timer.h" -#include -#include "environment.h" - -using namespace sp; - -WatchdogTimer::WatchdogTimer(Environment *env) - : env_(env), - terminate_(false), - mainthread_(ke::GetCurrentThreadId()), - last_frame_id_(0), - second_timeout_(false), - timedout_(false) -{ -} - -WatchdogTimer::~WatchdogTimer() -{ - assert(!thread_); -} - -bool -WatchdogTimer::Initialize(size_t timeout_ms) -{ - if (thread_) - return false; - - timeout_ms_ = timeout_ms; - - thread_ = new ke::Thread(this, "SM Watchdog"); - if (!thread_->Succeeded()) - return false; - - return true; -} - -void -WatchdogTimer::Shutdown() -{ - if (terminate_ || !thread_) - return; - - { - ke::AutoLock lock(&cv_); - terminate_ = true; - cv_.Notify(); - } - thread_->Join(); - thread_ = NULL; -} - -void -WatchdogTimer::Run() -{ - ke::AutoLock lock(&cv_); - - // Initialize the frame id, so we don't have to wait longer on startup. - last_frame_id_ = env_->FrameId(); - - while (!terminate_) { - ke::WaitResult rv = cv_.Wait(timeout_ms_ / 2); - if (terminate_) - return; - - if (rv == ke::Wait_Error) - return; - - if (rv != ke::Wait_Timeout) - continue; - - // We reached a timeout. If the current frame is not equal to the last - // frame, then we assume the server is still moving enough to process - // frames. We also make sure JIT code is actually on the stack, since - // our concept of frames won't move if JIT code is not running. - // - // Note that it's okay if these two race: it's just a heuristic, and - // worst case, we'll miss something that might have timed out but - // ended up resuming. - uintptr_t frame_id = env_->FrameId(); - if (frame_id != last_frame_id_ || !env_->RunningCode()) { - last_frame_id_ = frame_id; - second_timeout_ = false; - continue; - } - - // We woke up with the same frame. We might be timing out. Wait another - // time to see if so. - if (!second_timeout_) { - second_timeout_ = true; - continue; - } - - { - // Prevent the JIT from linking or destroying runtimes and functions. - ke::AutoLock lock(env_->lock()); - - // Set the timeout notification bit. If this is detected before any patched - // JIT backedges are reached, the main thread will attempt to acquire the - // monitor lock, and block until we call Wait(). - timedout_ = true; - - // Patch all jumps. This can race with the main thread's execution since - // all code writes are 32-bit integer instruction operands, which are - // guaranteed to be atomic on x86. - env_->PatchAllJumpsForTimeout(); - } - - // The JIT will be free to compile new functions while we wait, but it will - // see the timeout bit set above and immediately bail out. - cv_.Wait(); - - second_timeout_ = false; - - // Reset the last frame ID to something unlikely to be chosen again soon. - last_frame_id_--; - - // It's possible that Shutdown() raced with the timeout, and if so, we - // must leave now to prevent a deadlock. - if (terminate_) - return; - } -} - -bool -WatchdogTimer::NotifyTimeoutReceived() -{ - // We are guaranteed that the watchdog thread is waiting for our - // notification, and is therefore blocked. We take the JIT lock - // anyway for sanity. - { - ke::AutoLock lock(env_->lock()); - env_->UnpatchAllJumpsFromTimeout(); - } - - timedout_ = false; - - // Wake up the watchdog thread, it's okay to keep processing now. - ke::AutoLock lock(&cv_); - cv_.Notify(); - return false; -} - -bool -WatchdogTimer::HandleInterrupt() -{ - if (timedout_) - return NotifyTimeoutReceived(); - return true; -} diff --git a/sourcepawn/vm/watchdog_timer.h b/sourcepawn/vm/watchdog_timer.h deleted file mode 100644 index e7242241..00000000 --- a/sourcepawn/vm/watchdog_timer.h +++ /dev/null @@ -1,67 +0,0 @@ -// vim: set ts=8 sts=2 sw=2 tw=99 et: -// -// This file is part of SourcePawn. -// -// SourcePawn is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// SourcePawn is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU General Public License -// along with SourcePawn. If not, see . -#ifndef _include_sourcepawn_watchdog_timer_posix_h_ -#define _include_sourcepawn_watchdog_timer_posix_h_ - -#include -#include -#include - -namespace sp { - -class Environment; - -typedef bool (*WatchdogCallback)(); - -class WatchdogTimer : public ke::IRunnable -{ - public: - WatchdogTimer(Environment *env); - ~WatchdogTimer(); - - bool Initialize(size_t timeout_ms); - void Shutdown(); - - // Called from main thread. - bool NotifyTimeoutReceived(); - bool HandleInterrupt(); - - private: - // Watchdog thread. - void Run(); - - private: - Environment *env_; - - bool terminate_; - size_t timeout_ms_; - ke::ThreadId mainthread_; - - ke::AutoPtr thread_; - ke::ConditionVariable cv_; - - // Accessed only on the watchdog thread. - uintptr_t last_frame_id_; - bool second_timeout_; - - // Accessed only on the main thread. - bool timedout_; -}; - -} // namespace sp - -#endif // _include_sourcepawn_watchdog_timer_posix_h_ diff --git a/sourcepawn/vm/x86/assembler-x86.cpp b/sourcepawn/vm/x86/assembler-x86.cpp deleted file mode 100644 index 93884f1c..00000000 --- a/sourcepawn/vm/x86/assembler-x86.cpp +++ /dev/null @@ -1,33 +0,0 @@ -/** - * vim: set ts=8 sts=2 sw=2 tw=99 et: - * ============================================================================= - * SourcePawn JIT SDK - * Copyright (C) 2004-2008 AlliedModders LLC. All rights reserved. - * ============================================================================= - * - * This program is free software; you can redistribute it and/or modify it under - * the terms of the GNU General Public License, version 3.0, as published by the - * Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS - * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more - * details. - * - * You should have received a copy of the GNU General Public License along with - * this program. If not, see . - * - * As a special exception, AlliedModders LLC gives you permission to link the - * code of this program (as well as its derivative works) to "Half-Life 2," the - * "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software - * by the Valve Corporation. You must obey the GNU General Public License in - * all respects for all other code used. Additionally, AlliedModders LLC grants - * this exception to all derivative works. AlliedModders LLC defines further - * exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007), - * or . - * - * Version: $Id$ - */ -#include "assembler-x86.h" - -CPUFeatures AssemblerX86::X86Features; diff --git a/sourcepawn/vm/x86/assembler-x86.h b/sourcepawn/vm/x86/assembler-x86.h deleted file mode 100644 index b766bb54..00000000 --- a/sourcepawn/vm/x86/assembler-x86.h +++ /dev/null @@ -1,977 +0,0 @@ -/** - * vim: set ts=8 sts=2 sw=2 tw=99 et: - * ============================================================================= - * SourcePawn JIT SDK - * Copyright (C) 2004-2008 AlliedModders LLC. All rights reserved. - * ============================================================================= - * - * This program is free software; you can redistribute it and/or modify it under - * the terms of the GNU General Public License, version 3.0, as published by the - * Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS - * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more - * details. - * - * You should have received a copy of the GNU General Public License along with - * this program. If not, see . - * - * As a special exception, AlliedModders LLC gives you permission to link the - * code of this program (as well as its derivative works) to "Half-Life 2," the - * "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software - * by the Valve Corporation. You must obey the GNU General Public License in - * all respects for all other code used. Additionally, AlliedModders LLC grants - * this exception to all derivative works. AlliedModders LLC defines further - * exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007), - * or . - * - * Version: $Id$ - */ -#ifndef _include_sourcepawn_assembler_x86_h__ -#define _include_sourcepawn_assembler_x86_h__ - -#include -#include -#include - -struct Register -{ - const char *name() const { - static const char *names[] = { - "eax", "ecx", "edx", "ebx", "esp", "ebp", "esi", "edi" - }; - return names[code]; - } - - int code; - - bool operator == (const Register &other) const { - return code == other.code; - } - bool operator != (const Register &other) const { - return code != other.code; - } -}; - -// X86 has an ancient FPU (called x87) which has a stack of registers -// numbered st0 through st7. -struct FpuRegister -{ - const char *name() const { - static const char *names[] = { - "st0", "st1", "st2", "st3", "st4", "st5", "st6", "st7" - }; - return names[code]; - } - - int code; - - bool operator == (const FpuRegister &other) const { - return code == other.code; - } - bool operator != (const FpuRegister &other) const { - return code != other.code; - } -}; - -struct FloatRegister -{ - const char *name() const { - static const char *names[] = { - "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5", "xmm6", "xmm7" - }; - return names[code]; - } - - int code; - - bool operator == (const FloatRegister &other) const { - return code == other.code; - } - bool operator != (const FloatRegister &other) const { - return code != other.code; - } -}; - -struct CPUFeatures -{ - CPUFeatures() - { - memset(this, 0, sizeof(*this)); - } - - bool fpu; - bool mmx; - bool sse; - bool sse2; - bool sse3; - bool ssse3; - bool sse4_1; - bool sse4_2; - bool avx; - bool avx2; -}; - -const Register eax = { 0 }; -const Register ecx = { 1 }; -const Register edx = { 2 }; -const Register ebx = { 3 }; -const Register esp = { 4 }; -const Register ebp = { 5 }; -const Register esi = { 6 }; -const Register edi = { 7 }; - -const Register r8_al = { 0 }; -const Register r8_cl = { 1 }; -const Register r8_dl = { 2 }; -const Register r8_bl = { 3 }; -const Register r8_ah = { 4 }; -const Register r8_ch = { 5 }; -const Register r8_dh = { 6 }; -const Register r8_bh = { 7 }; - -const FpuRegister st0 = { 0 }; -const FpuRegister st1 = { 1 }; -const FpuRegister st2 = { 2 }; -const FpuRegister st3 = { 3 }; -const FpuRegister st4 = { 4 }; -const FpuRegister st5 = { 5 }; -const FpuRegister st6 = { 6 }; -const FpuRegister st7 = { 7 }; - -const FloatRegister xmm0 = { 0 }; -const FloatRegister xmm1 = { 1 }; -const FloatRegister xmm2 = { 2 }; -const FloatRegister xmm3 = { 3 }; -const FloatRegister xmm4 = { 4 }; -const FloatRegister xmm5 = { 5 }; -const FloatRegister xmm6 = { 6 }; -const FloatRegister xmm7 = { 7 }; - -static const uint8_t kModeDisp0 = 0; -static const uint8_t kModeDisp8 = 1; -static const uint8_t kModeDisp32 = 2; -static const uint8_t kModeReg = 3; -static const uint8_t kNoIndex = 4; -static const uint8_t kSIB = 4; -static const uint8_t kRIP = 5; - -enum ConditionCode { - overflow, - no_overflow, - below, - not_below, - equal, - not_equal, - not_above, - above, - negative, - not_negative, - even_parity, - odd_parity, - less, - not_less, - not_greater, - greater, - - zero = equal, - not_zero = not_equal, - less_equal = not_greater, - below_equal = not_above, - greater_equal = not_less, - above_equal = not_below, - parity = even_parity, - not_parity = odd_parity -}; - -enum Scale { - NoScale, - ScaleTwo, - ScaleFour, - ScaleEight, - ScalePointer = ScaleFour -}; - -struct Operand -{ - friend class AssemblerX86; - - public: - Operand(Register reg, int32_t disp) { - if (reg == esp) { - // If the reg is esp, we need a SIB encoding. - if (disp == 0) - sib_disp0(NoScale, kNoIndex, reg.code); - else if (disp >= SCHAR_MIN && disp <= SCHAR_MAX) - sib_disp8(NoScale, kNoIndex, reg.code, disp); - else - sib_disp32(NoScale, kNoIndex, reg.code, disp); - } else if (disp == 0 && reg != ebp) { - // note, [ebp+0] is disp32/rip - modrm_disp0(reg.code); - } else if (disp >= SCHAR_MIN && disp <= SCHAR_MAX) { - modrm_disp8(reg.code, disp); - } else { - modrm_disp32(reg.code, disp); - } - } - - Operand(Register base, Scale scale, int32_t disp = 0) { - if (disp == 0 && base != ebp) - sib_disp0(scale, kNoIndex, base.code); - else if (disp >= SCHAR_MIN && disp <= SCHAR_MAX) - sib_disp8(scale, kNoIndex, base.code, disp); - else - sib_disp32(scale, kNoIndex, base.code, disp); - } - - Operand(Register base, Register index, Scale scale, int32_t disp = 0) { - assert(index.code != kNoIndex); - if (disp == 0 && base != ebp) - sib_disp0(scale, index.code, base.code); - else if (disp >= SCHAR_MIN && disp <= SCHAR_MAX) - sib_disp8(scale, index.code, base.code, disp); - else - sib_disp32(scale, index.code, base.code, disp); - } - - explicit Operand(ExternalAddress address) { - modrm(kModeDisp0, kRIP); - *reinterpret_cast(bytes_ + 1) = address.address(); - } - - bool isRegister() const { - return mode() == kModeReg; - } - bool isRegister(Register r) const { - return mode() == kModeReg && rm() == r.code; - } - int registerCode() const { - return rm(); - } - - uint8_t getByte(size_t index) const { - assert(index < length()); - return bytes_[index]; - } - - size_t length() const { - if (mode() == kModeDisp0 && rm() == kRIP) - return 5; - size_t sib = (mode() != kModeReg && rm() == kSIB); - if (mode() == kModeDisp32) - return 5 + sib; - if (mode() == kModeDisp8) - return 2 + sib; - return 1 + sib; - } - - private: - explicit Operand(Register reg) { - modrm(kModeReg, reg.code); - } - - void modrm(uint8_t mode, uint8_t rm) { - assert(mode <= 3); - assert(rm <= 7); - bytes_[0] = (mode << 6) | rm; - } - void modrm_disp0(uint8_t rm) { - modrm(kModeDisp0, rm); - } - void modrm_disp8(uint8_t rm, int8_t disp) { - modrm(kModeDisp8, rm); - bytes_[1] = disp; - } - void modrm_disp32(uint8_t rm, int32_t disp) { - modrm(kModeDisp32, rm); - *reinterpret_cast(bytes_ + 1) = disp; - } - void sib(uint8_t mode, Scale scale, uint8_t index, uint8_t base) { - modrm(mode, kSIB); - - assert(scale <= 3); - assert(index <= 7); - assert(base <= 7); - bytes_[1] = (uint8_t(scale) << 6) | (index << 3) | base; - } - void sib_disp0(Scale scale, uint8_t index, uint8_t base) { - sib(kModeDisp0, scale, index, base); - } - void sib_disp8(Scale scale, uint8_t index, uint8_t base, int8_t disp) { - sib(kModeDisp8, scale, index, base); - bytes_[2] = disp; - } - void sib_disp32(Scale scale, uint8_t index, uint8_t base, int32_t disp) { - sib(kModeDisp32, scale, index, base); - *reinterpret_cast(bytes_ + 2) = disp; - } - - private: - uint8_t rm() const { - return bytes_[0] & 7; - } - uint8_t mode() const { - return bytes_[0] >> 6; - } - - private: - uint8_t bytes_[6]; -}; - -class AssemblerX86 : public Assembler -{ - private: - // List of processor features; to be used, this must be filled in at - // startup. - static CPUFeatures X86Features; - - public: - static void SetFeatures(const CPUFeatures &features) { - X86Features = features; - } - static const CPUFeatures &Features() { - return X86Features; - } - - void movl(Register dest, Register src) { - emit1(0x89, src.code, dest.code); - } - void movl(Register dest, const Operand &src) { - emit1(0x8b, dest.code, src); - } - void movl(const Operand &dest, Register src) { - emit1(0x89, src.code, dest); - } - void movl(Register dest, int32_t imm) { - emit1(0xb8 + dest.code); - writeInt32(imm); - } - void movl(const Operand &dest, int32_t imm) { - if (dest.isRegister()) - emit1(0xb8 + dest.registerCode()); - else - emit1(0xc7, 0, dest); - writeInt32(imm); - } - void movw(const Operand &dest, Register src) { - emit1(0x89, src.code, dest); - } - void movw(Register dest, const Operand &src) { - emit1(0x8b, dest.code, src); - } - void movb(const Operand &dest, Register src) { - emit1(0x88, src.code, dest); - } - void movb(Register dest, const Operand &src) { - emit1(0x8a, dest.code, src); - } - void movzxb(Register dest, const Operand &src) { - emit2(0x0f, 0xb6, dest.code, src); - } - void movzxb(Register dest, const Register src) { - emit2(0x0f, 0xb6, dest.code, src.code); - } - void movzxw(Register dest, const Operand &src) { - emit2(0x0f, 0xb7, dest.code, src); - } - void movzxw(Register dest, const Register src) { - emit2(0x0f, 0xb7, dest.code, src.code); - } - - void lea(Register dest, const Operand &src) { - emit1(0x8d, dest.code, src); - } - - void xchgl(Register dest, Register src) { - if (src == eax) - emit1(0x90 + dest.code); - else if (dest == eax) - emit1(0x90 + src.code); - else - emit1(0x87, src.code, dest.code); - } - - void shll_cl(Register dest) { - shift_cl(dest.code, 4); - } - void shll(Register dest, uint8_t imm) { - shift_imm(dest.code, 4, imm); - } - void shll(const Operand &dest, uint8_t imm) { - shift_imm(dest, 4, imm); - } - void shrl_cl(Register dest) { - shift_cl(dest.code, 5); - } - void shrl(Register dest, uint8_t imm) { - shift_imm(dest.code, 5, imm); - } - void shrl(const Operand &dest, uint8_t imm) { - shift_imm(dest, 5, imm); - } - void sarl_cl(Register dest) { - shift_cl(dest.code, 7); - } - void sarl(Register dest, uint8_t imm) { - shift_imm(dest.code, 7, imm); - } - void sarl(const Operand &dest, uint8_t imm) { - shift_imm(dest, 7, imm); - } - - void cmpl(Register left, int32_t imm) { - alu_imm(7, imm, Operand(left)); - } - void cmpl(const Operand &left, int32_t imm) { - alu_imm(7, imm, left); - } - void cmpl(Register left, Register right) { - emit1(0x39, right.code, left.code); - } - void cmpl(const Operand &left, Register right) { - emit1(0x39, right.code, left); - } - void cmpl(Register left, const Operand &right) { - emit1(0x3b, left.code, right); - } - void andl(Register dest, int32_t imm) { - alu_imm(4, imm, Operand(dest)); - } - void andl(const Operand &dest, int32_t imm) { - alu_imm(4, imm, dest); - } - void andl(Register dest, Register src) { - emit1(0x21, src.code, dest.code); - } - void andl(const Operand &dest, Register src) { - emit1(0x21, src.code, dest); - } - void andl(Register dest, const Operand &src) { - emit1(0x23, dest.code, src); - } - void orl(Register dest, Register src) { - emit1(0x09, src.code, dest.code); - } - void orl(const Operand &dest, Register src) { - emit1(0x09, src.code, dest); - } - void orl(Register dest, const Operand &src) { - emit1(0x0b, dest.code, src); - } - void xorl(Register dest, Register src) { - emit1(0x31, src.code, dest.code); - } - void xorl(const Operand &dest, Register src) { - emit1(0x31, src.code, dest); - } - void xorl(Register dest, const Operand &src) { - emit1(0x33, dest.code, src); - } - - void subl(Register dest, Register src) { - emit1(0x29, src.code, dest.code); - } - void subl(const Operand &dest, Register src) { - emit1(0x29, src.code, dest); - } - void subl(Register dest, const Operand &src) { - emit1(0x2b, dest.code, src); - } - void subl(Register dest, int32_t imm) { - alu_imm(5, imm, Operand(dest)); - } - void subl(const Operand &dest, int32_t imm) { - alu_imm(5, imm, dest); - } - void addl(Register dest, Register src) { - emit1(0x01, src.code, dest.code); - } - void addl(const Operand &dest, Register src) { - emit1(0x01, src.code, dest); - } - void addl(Register dest, const Operand &src) { - emit1(0x03, dest.code, src); - } - void addl(Register dest, int32_t imm) { - alu_imm(0, imm, Operand(dest)); - } - void addl(const Operand &dest, int32_t imm) { - alu_imm(0, imm, dest); - } - - void imull(Register dest, const Operand &src) { - emit2(0x0f, 0xaf, dest.code, src); - } - void imull(Register dest, Register src) { - emit2(0x0f, 0xaf, dest.code, src.code); - } - void imull(Register dest, const Operand &src, int32_t imm) { - if (imm >= SCHAR_MIN && imm <= SCHAR_MAX) { - emit1(0x6b, dest.code, src); - *pos_++ = imm; - } else { - emit1(0x69, dest.code, src); - writeInt32(imm); - } - } - void imull(Register dest, Register src, int32_t imm) { - imull(dest, Operand(src), imm); - } - - void testl(const Operand &op1, Register op2) { - emit1(0x85, op2.code, op1); - } - void testl(Register op1, Register op2) { - emit1(0x85, op2.code, op1.code); - } - void set(ConditionCode cc, const Operand &dest) { - emit2(0x0f, 0x90 + uint8_t(cc), 0, dest); - } - void set(ConditionCode cc, Register dest) { - emit2(0x0f, 0x90 + uint8_t(cc), 0, dest.code); - } - void negl(Register srcdest) { - emit1(0xf7, 3, srcdest.code); - } - void negl(const Operand &srcdest) { - emit1(0xf7, 3, srcdest); - } - void notl(Register srcdest) { - emit1(0xf7, 2, srcdest.code); - } - void notl(const Operand &srcdest) { - emit1(0xf7, 2, srcdest); - } - void idivl(Register dividend) { - emit1(0xf7, 7, dividend.code); - } - void idivl(const Operand ÷nd) { - emit1(0xf7, 7, dividend); - } - - void ret() { - emit1(0xc3); - } - void cld() { - emit1(0xfc); - } - void push(Register reg) { - emit1(0x50 + reg.code); - } - void push(const Operand &src) { - if (src.isRegister()) - emit1(0x50 + src.registerCode()); - else - emit1(0xff, 6, src); - } - void push(int32_t imm) { - emit1(0x68); - writeInt32(imm); - } - void pop(Register reg) { - emit1(0x58 + reg.code); - } - void pop(const Operand &src) { - if (src.isRegister()) - emit1(0x58 + src.registerCode()); - else - emit1(0x8f, 0, src); - } - - void rep_movsb() { - emit2(0xf3, 0xa4); - } - void rep_movsd() { - emit2(0xf3, 0xa5); - } - void rep_stosd() { - emit2(0xf3, 0xab); - } - void breakpoint() { - emit1(0xcc); - } - - void fld32(const Operand &src) { - emit1(0xd9, 0, src); - } - void fild32(const Operand &src) { - emit1(0xdb, 0, src); - } - void fistp32(const Operand &dest) { - emit1(0xdb, 3, dest); - } - void fadd32(const Operand &src) { - emit1(0xd8, 0, src); - } - void fsub32(const Operand &src) { - emit1(0xd8, 4, src); - } - void fmul32(const Operand &src) { - emit1(0xd8, 1, src); - } - void fdiv32(const Operand &src) { - emit1(0xd8, 6, src); - } - void fstp32(const Operand &dest) { - emit1(0xd9, 3, dest); - } - void fstp(FpuRegister src) { - emit2(0xdd, 0xd8 + src.code); - } - void fldcw(const Operand &src) { - emit1(0xd9, 5, src); - } - void fstcw(const Operand &dest) { - emit2(0x9b, 0xd9, 7, dest); - } - void fsubr32(const Operand &src) { - emit1(0xd8, 5, src); - } - void fldz() { - emit2(0xd9, 0xee); - } - - // Compare st0 with stN. - void fucomip(FpuRegister other) { - emit2(0xdf, 0xe8 + other.code); - } - - // At least one argument of these forms must be st0. - void fadd32(FpuRegister dest, FpuRegister src) { - assert(dest == st0 || src == st0); - if (dest == st0) - emit2(0xd8, 0xc0 + dest.code); - else - emit2(0xdc, 0xc0 + src.code); - } - - void jmp32(Label *dest) { - emit1(0xe9); - emitJumpTarget(dest); - } - void jmp(Label *dest) { - int8_t d8; - if (canEmitSmallJump(dest, &d8)) { - emit2(0xeb, d8); - } else { - emit1(0xe9); - emitJumpTarget(dest); - } - } - void jmp(Register target) { - emit1(0xff, 4, target.code); - } - void jmp(const Operand &target) { - emit1(0xff, 4, target); - } - void j32(ConditionCode cc, Label *dest) { - emit2(0x0f, 0x80 + uint8_t(cc)); - emitJumpTarget(dest); - } - void j(ConditionCode cc, Label *dest) { - int8_t d8; - if (canEmitSmallJump(dest, &d8)) { - emit2(0x70 + uint8_t(cc), d8); - } else { - emit2(0x0f, 0x80 + uint8_t(cc)); - emitJumpTarget(dest); - } - } - void call(Label *dest) { - emit1(0xe8); - emitJumpTarget(dest); - } - void bind(Label *target) { - if (outOfMemory()) { - // If we ran out of memory, the code stream is potentially invalid and - // we cannot use the embedded linked list. - target->bind(pc()); - return; - } - - assert(!target->bound()); - uint32_t status = target->status(); - while (Label::More(status)) { - // Grab the offset. It should be at least a 1byte op + rel32. - uint32_t offset = Label::ToOffset(status); - assert(offset >= 5); - - // Grab the delta from target to pc. - ptrdiff_t delta = pos_ - (buffer() + offset); - assert(delta >= INT_MIN && delta <= INT_MAX); - - int32_t *p = reinterpret_cast(buffer() + offset - 4); - status = *p; - *p = delta; - } - target->bind(pc()); - } - - void bind(DataLabel *address) { - if (outOfMemory()) - return; - if (address->used()) { - uint32_t offset = DataLabel::ToOffset(address->status()); - *reinterpret_cast(buffer() + offset - 4) = position() - int32_t(offset); - } - address->bind(pc()); - } - void movl(Register dest, DataLabel *src) { - emit1(0xb8 + dest.code); - if (src->bound()) { - writeInt32(int32_t(src->offset()) - (position() + 4)); - } else { - writeInt32(0xabcdef0); - src->use(pc()); - } - if (!local_refs_.append(pc())) - outOfMemory_ = true; - } - void emit_absolute_address(Label *address) { - if (address->bound()) - writeUint32(int32_t(address->offset()) - (position() + 4)); - else - writeUint32(address->addPending(position() + 4)); - if (!local_refs_.append(pc())) - outOfMemory_ = true; - } - - void call(Register target) { - emit1(0xff, 2, target.code); - } - void call(const Operand &target) { - emit1(0xff, 2, target); - } - void call(ExternalAddress address) { - emit1(0xe8); - writeInt32(address.value()); - if (!external_refs_.append(pc())) - outOfMemory_ = true; - } - void jmp(ExternalAddress address) { - assert(sizeof(address) == sizeof(int32_t)); - emit1(0xe9); - writeInt32(address.value()); - if (!external_refs_.append(pc())) - outOfMemory_ = true; - } - - void cpuid() { - emit2(0x0f, 0xa2); - } - - - // SSE operations can only be used if the feature detection function has - // been run *and* detected the appropriate level of functionality. - void movss(FloatRegister dest, const Operand &src) { - assert(Features().sse); - emit3(0xf3, 0x0f, 0x10, dest.code, src); - } - void cvttss2si(Register dest, Register src) { - assert(Features().sse); - emit3(0xf3, 0x0f, 0x2c, dest.code, src.code); - } - void cvttss2si(Register dest, const Operand &src) { - assert(Features().sse); - emit3(0xf3, 0x0f, 0x2c, dest.code, src); - } - void cvtss2si(Register dest, Register src) { - assert(Features().sse); - emit3(0xf3, 0x0f, 0x2d, dest.code, src.code); - } - void cvtss2si(Register dest, const Operand &src) { - assert(Features().sse); - emit3(0xf3, 0x0f, 0x2d, dest.code, src); - } - void cvtsi2ss(FloatRegister dest, Register src) { - assert(Features().sse); - emit3(0xf3, 0x0f, 0x2a, dest.code, src.code); - } - void cvtsi2ss(FloatRegister dest, const Operand &src) { - assert(Features().sse); - emit3(0xf3, 0x0f, 0x2a, dest.code, src); - } - void addss(FloatRegister dest, const Operand &src) { - assert(Features().sse); - emit3(0xf3, 0x0f, 0x58, dest.code, src); - } - void subss(FloatRegister dest, const Operand &src) { - assert(Features().sse); - emit3(0xf3, 0x0f, 0x5c, dest.code, src); - } - void mulss(FloatRegister dest, const Operand &src) { - assert(Features().sse); - emit3(0xf3, 0x0f, 0x59, dest.code, src); - } - void divss(FloatRegister dest, const Operand &src) { - assert(Features().sse); - emit3(0xf3, 0x0f, 0x5e, dest.code, src); - } - void xorps(FloatRegister dest, FloatRegister src) { - assert(Features().sse); - emit2(0x0f, 0x57, src.code, dest.code); - } - - void ucomiss(FloatRegister left, FloatRegister right) { - emit2(0x0f, 0x2e, right.code, left.code); - } - void ucomiss(const Operand &left, FloatRegister right) { - emit2(0x0f, 0x2e, right.code, left); - } - - // SSE2-only instructions. - void movd(Register dest, FloatRegister src) { - assert(Features().sse2); - emit3(0x66, 0x0f, 0x7e, dest.code, src.code); - } - void movd(Register dest, const Operand &src) { - assert(Features().sse2); - emit3(0x66, 0x0f, 0x7e, dest.code, src); - } - - static void PatchRel32Absolute(uint8_t *ip, void *ptr) { - int32_t delta = uint32_t(ptr) - uint32_t(ip); - *reinterpret_cast(ip - 4) = delta; - } - - void emitToExecutableMemory(void *code) { - assert(!outOfMemory()); - - // Relocate anything we emitted as rel32 with an external pointer. - uint8_t *base = reinterpret_cast(code); - memcpy(base, buffer(), length()); - for (size_t i = 0; i < external_refs_.length(); i++) { - size_t offset = external_refs_[i]; - PatchRel32Absolute(base + offset, *reinterpret_cast(base + offset - 4)); - } - - // Relocate everything we emitted as an abs32 with an internal offset. Note - // that in the code stream, we use relative offsets so we can use both Label - // and DataLabel. - for (size_t i = 0; i < local_refs_.length(); i++) { - size_t offset = local_refs_[i]; - int32_t delta = *reinterpret_cast(base + offset - 4); - *reinterpret_cast(base + offset - 4) = base + offset + delta; - } - } - - void align(uint32_t bytes) { - int32_t delta = (pc() & ~(bytes - 1)) + bytes - pc(); - for (int32_t i = 0; i < delta; i++) - emit1(0xcc); - } - - private: - bool canEmitSmallJump(Label *dest, int8_t *deltap) { - if (!dest->bound()) - return false; - - // All small jumps are assumed to be 2 bytes. - ptrdiff_t delta = ptrdiff_t(dest->offset()) - (position() + 2); - if (delta < SCHAR_MIN || delta > SCHAR_MAX) - return false; - *deltap = delta; - return true; - } - void emitJumpTarget(Label *dest) { - if (dest->bound()) { - ptrdiff_t delta = ptrdiff_t(dest->offset()) - (position() + 4); - assert(delta >= INT_MIN && delta <= INT_MAX); - writeInt32(delta); - } else { - writeUint32(dest->addPending(position() + 4)); - } - } - - void emit(uint8_t reg, const Operand &operand) { - *pos_++ = operand.getByte(0) | (reg << 3); - size_t length = operand.length(); - for (size_t i = 1; i < length; i++) - *pos_++ = operand.getByte(i); - } - - void emit1(uint8_t opcode) { - ensureSpace(); - *pos_++ = opcode; - } - void emit1(uint8_t opcode, uint8_t reg, uint8_t opreg) { - ensureSpace(); - assert(reg <= 7); - assert(opreg <= 7); - *pos_++ = opcode; - *pos_++ = (kModeReg << 6) | (reg << 3) | opreg; - } - void emit1(uint8_t opcode, uint8_t reg, const Operand &operand) { - ensureSpace(); - assert(reg <= 7); - *pos_++ = opcode; - emit(reg, operand); - } - - void emit2(uint8_t prefix, uint8_t opcode) { - ensureSpace(); - *pos_++ = prefix; - *pos_++ = opcode; - } - void emit2(uint8_t prefix, uint8_t opcode, uint8_t reg, uint8_t opreg) { - emit2(prefix, opcode); - assert(reg <= 7); - *pos_++ = (kModeReg << 6) | (reg << 3) | opreg; - } - void emit2(uint8_t prefix, uint8_t opcode, uint8_t reg, const Operand &operand) { - emit2(prefix, opcode); - emit(reg, operand); - } - - void emit3(uint8_t prefix1, uint8_t prefix2, uint8_t opcode) { - ensureSpace(); - *pos_++ = prefix1; - *pos_++ = prefix2; - *pos_++ = opcode; - } - void emit3(uint8_t prefix1, uint8_t prefix2, uint8_t opcode, uint8_t reg, uint8_t opreg) { - emit3(prefix1, prefix2, opcode); - assert(reg <= 7); - *pos_++ = (kModeReg << 6) | (reg << 3) | opreg; - } - void emit3(uint8_t prefix1, uint8_t prefix2, uint8_t opcode, uint8_t reg, const Operand &operand) { - emit3(prefix1, prefix2, opcode); - emit(reg, operand); - } - - template - void shift_cl(const T &t, uint8_t r) { - emit1(0xd3, r, t); - } - - template - void shift_imm(const T &t, uint8_t r, int32_t imm) { - if (imm == 1) { - emit1(0xd1, r, t); - } else { - emit1(0xc1, r, t); - *pos_++ = imm & 0x1F; - } - } - void alu_imm(uint8_t r, int32_t imm, const Operand &operand) { - if (imm >= SCHAR_MIN && imm <= SCHAR_MAX) { - emit1(0x83, r, operand); - *pos_++ = uint8_t(imm & 0xff); - } else if (operand.isRegister(eax)) { - emit1(0x05 | (r << 3)); - writeInt32(imm); - } else { - emit1(0x81, r, operand); - writeInt32(imm); - } - } - - private: - ke::Vector external_refs_; - ke::Vector local_refs_; -}; - -#endif // _include_sourcepawn_assembler_x86_h__ - diff --git a/sourcepawn/vm/x86/code-stubs-x86.cpp b/sourcepawn/vm/x86/code-stubs-x86.cpp deleted file mode 100644 index 0662c859..00000000 --- a/sourcepawn/vm/x86/code-stubs-x86.cpp +++ /dev/null @@ -1,141 +0,0 @@ -// vim: set sts=2 ts=8 sw=2 tw=99 et: -// -// Copyright (C) 2006-2015 AlliedModders LLC -// -// This file is part of SourcePawn. SourcePawn is free software: you can -// redistribute it and/or modify it under the terms of the GNU General Public -// License as published by the Free Software Foundation, either version 3 of -// the License, or (at your option) any later version. -// -// You should have received a copy of the GNU General Public License along with -// SourcePawn. If not, see http://www.gnu.org/licenses/. -// -#include -#include "code-stubs.h" -#include "x86-utils.h" -#include "jit_x86.h" -#include "environment.h" - -using namespace sp; -using namespace SourcePawn; - -#define __ masm. - -bool -CodeStubs::InitializeFeatureDetection() -{ - MacroAssemblerX86 masm; - MacroAssemblerX86::GenerateFeatureDetection(masm); - void *code = LinkCode(env_, masm); - if (!code) - return false; - MacroAssemblerX86::RunFeatureDetection(code); - return true; -} - - -bool -CodeStubs::CompileInvokeStub() -{ - AssemblerX86 masm; - - __ push(ebp); - __ movl(ebp, esp); - - __ push(esi); // ebp - 4 - __ push(edi); // ebp - 8 - __ push(ebx); // ebp - 12 - __ push(esp); // ebp - 16 - - // ebx = cx - __ movl(ebx, Operand(ebp, 8 + 4 * 0)); - - // ecx = code - __ movl(ecx, Operand(ebp, 8 + 4 * 1)); - - // eax = cx->memory - __ movl(eax, Operand(ebx, PluginContext::offsetOfMemory())); - - // Set up run-time registers. - __ movl(edi, Operand(ebx, PluginContext::offsetOfSp())); - __ addl(edi, eax); - __ movl(esi, eax); - __ movl(ebx, edi); - - // Align the stack. - __ andl(esp, 0xfffffff0); - - // Set up the last piece of the invoke frame. This lets us find the bounds - // of the call stack. - __ movl(eax, intptr_t(Environment::get())); - __ movl(eax, Operand(eax, Environment::offsetOfTopFrame())); - __ movl(Operand(eax, InvokeFrame::offsetOfEntrySp()), esp); - - // Call into plugin (align the stack first). - __ call(ecx); - - // Get input context, store rval. - __ movl(ecx, Operand(ebp, 8 + 4 * 2)); - __ movl(Operand(ecx, 0), pri); - - // Set no error. - __ movl(eax, SP_ERROR_NONE); - - // Store latest stk. If we have an error code, we'll jump directly to here, - // so eax will already be set. - Label ret; - __ bind(&ret); - __ subl(stk, dat); - __ movl(ecx, Operand(ebp, 8 + 4 * 0)); - __ movl(Operand(ecx, PluginContext::offsetOfSp()), stk); - - // Restore stack. - __ movl(esp, Operand(ebp, -16)); - - // Restore registers and gtfo. - __ pop(ebx); - __ pop(edi); - __ pop(esi); - __ pop(ebp); - __ ret(); - - // The universal emergency return will jump to here. - Label error; - __ bind(&error); - __ movl(ecx, Operand(ebp, 8 + 4 * 0)); // ret-path expects ecx = ctx - __ jmp(&ret); - - invoke_stub_ = LinkCode(env_, masm); - if (!invoke_stub_) - return false; - - return_stub_ = reinterpret_cast(invoke_stub_) + error.offset(); - return true; -} - -SPVM_NATIVE_FUNC -CodeStubs::CreateFakeNativeStub(SPVM_FAKENATIVE_FUNC callback, void *pData) -{ - AssemblerX86 masm; - - __ push(ebx); - __ push(edi); - __ push(esi); - __ movl(edi, Operand(esp, 16)); // store ctx - __ movl(esi, Operand(esp, 20)); // store params - __ movl(ebx, esp); - __ andl(esp, 0xfffffff0); - __ subl(esp, 4); - - __ push(intptr_t(pData)); - __ push(esi); - __ push(edi); - __ call(ExternalAddress((void *)callback)); - __ movl(esp, ebx); - __ pop(esi); - __ pop(edi); - __ pop(ebx); - __ ret(); - - return (SPVM_NATIVE_FUNC)LinkCode(env_, masm); -} diff --git a/sourcepawn/vm/x86/frames-x86.h b/sourcepawn/vm/x86/frames-x86.h deleted file mode 100644 index 35a90fc7..00000000 --- a/sourcepawn/vm/x86/frames-x86.h +++ /dev/null @@ -1,83 +0,0 @@ -// vim: set ts=8 sts=2 sw=2 tw=99 et: -// -// This file is part of SourcePawn. -// -// SourcePawn is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// SourcePawn is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU General Public License -// along with SourcePawn. If not, see . -#ifndef _include_sourcepawn_jit_frames_x86_h_ -#define _include_sourcepawn_jit_frames_x86_h_ - -#include - -namespace sp { - -using namespace SourcePawn; - -class PluginContext; - -// This is the layout of the stack in between each scripted function call. -struct JitFrame -{ - intptr_t align0; - intptr_t align1; - ucell_t function_cip; - void *return_address; - - static inline const JitFrame *FromSp(const intptr_t *sp) { - return reinterpret_cast(sp); - } -}; - -// When we're about to call a native, the stack pointer we store in the exit -// frame is such that (sp + sizeof(JitExitFrameForNative)) conforms to this -// structure. -// -// Note that it looks reversed compared to JitFrame because we capture the sp -// before saving registers and pushing arguments. -struct JitExitFrameForNative -{ - void *return_address; - PluginContext *cx; - union { - uint32_t native_index; - SPVM_NATIVE_FUNC fn; - } arg; - const cell_t *params; - cell_t saved_alt; - - static inline const JitExitFrameForNative *FromExitSp(const intptr_t *exit_sp) { - return reinterpret_cast( - reinterpret_cast(exit_sp) - sizeof(JitExitFrameForNative)); - } -}; - -// Unlke native frames, the exit_sp for these is created at the base address. -struct JitExitFrameForHelper -{ - void *return_address; - - static inline const JitExitFrameForHelper *FromExitSp(const intptr_t *exit_sp) { - return reinterpret_cast(exit_sp); - } - - bool isCompileFunction() const { - return !!return_address; - } - const JitFrame *prev() const { - return reinterpret_cast(this + 1); - } -}; - -} // namespace sp - -#endif // _include_sourcepawn_jit_frames_x86_h_ diff --git a/sourcepawn/vm/x86/jit_x86.cpp b/sourcepawn/vm/x86/jit_x86.cpp deleted file mode 100644 index 33dab470..00000000 --- a/sourcepawn/vm/x86/jit_x86.cpp +++ /dev/null @@ -1,1833 +0,0 @@ -/** - * vim: set ts=2 sw=2 tw=99 et: - * ============================================================================= - * SourceMod - * Copyright (C) 2004-2008 AlliedModders LLC. All rights reserved. - * ============================================================================= - * - * This program is free software; you can redistribute it and/or modify it under - * the terms of the GNU General Public License, version 3.0, as published by the - * Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS - * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more - * details. - * - * You should have received a copy of the GNU General Public License along with - * this program. If not, see . - * - * As a special exception, AlliedModders LLC gives you permission to link the - * code of this program (as well as its derivative works) to "Half-Life 2," the - * "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software - * by the Valve Corporation. You must obey the GNU General Public License in - * all respects for all other code used. Additionally, AlliedModders LLC grants - * this exception to all derivative works. AlliedModders LLC defines further - * exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007), - * or . - * - * Version: $Id$ - */ - -#include -#include -#include -#include "jit_x86.h" -#include "plugin-runtime.h" -#include "plugin-context.h" -#include "watchdog_timer.h" -#include "environment.h" -#include "code-stubs.h" -#include "x86-utils.h" - -using namespace sp; - -#if defined USE_UNGEN_OPCODES -#include "ungen_opcodes.h" -#endif - -#define __ masm. - -static inline ConditionCode -OpToCondition(OPCODE op) -{ - switch (op) { - case OP_EQ: - case OP_JEQ: - return equal; - case OP_NEQ: - case OP_JNEQ: - return not_equal; - case OP_SLESS: - case OP_JSLESS: - return less; - case OP_SLEQ: - case OP_JSLEQ: - return less_equal; - case OP_SGRTR: - case OP_JSGRTR: - return greater; - case OP_SGEQ: - case OP_JSGEQ: - return greater_equal; - default: - assert(false); - return negative; - } -} - -#if 0 && !defined NDEBUG -static const char * -GetFunctionName(const sp_plugin_t *plugin, uint32_t offs) -{ - if (!plugin->debug.unpacked) { - uint32_t max, iter; - sp_fdbg_symbol_t *sym; - sp_fdbg_arraydim_t *arr; - uint8_t *cursor = (uint8_t *)(plugin->debug.symbols); - - max = plugin->debug.syms_num; - for (iter = 0; iter < max; iter++) { - sym = (sp_fdbg_symbol_t *)cursor; - - if (sym->ident == sp::IDENT_FUNCTION && sym->codestart <= offs && sym->codeend > offs) - return plugin->debug.stringbase + sym->name; - - if (sym->dimcount > 0) { - cursor += sizeof(sp_fdbg_symbol_t); - arr = (sp_fdbg_arraydim_t *)cursor; - cursor += sizeof(sp_fdbg_arraydim_t) * sym->dimcount; - continue; - } - - cursor += sizeof(sp_fdbg_symbol_t); - } - } else { - uint32_t max, iter; - sp_u_fdbg_symbol_t *sym; - sp_u_fdbg_arraydim_t *arr; - uint8_t *cursor = (uint8_t *)(plugin->debug.symbols); - - max = plugin->debug.syms_num; - for (iter = 0; iter < max; iter++) { - sym = (sp_u_fdbg_symbol_t *)cursor; - - if (sym->ident == sp::IDENT_FUNCTION && sym->codestart <= offs && sym->codeend > offs) - return plugin->debug.stringbase + sym->name; - - if (sym->dimcount > 0) { - cursor += sizeof(sp_u_fdbg_symbol_t); - arr = (sp_u_fdbg_arraydim_t *)cursor; - cursor += sizeof(sp_u_fdbg_arraydim_t) * sym->dimcount; - continue; - } - - cursor += sizeof(sp_u_fdbg_symbol_t); - } - } - - return NULL; -} -#endif - -CompiledFunction * -sp::CompileFunction(PluginRuntime *prt, cell_t pcode_offs, int *err) -{ - Compiler cc(prt, pcode_offs); - CompiledFunction *fun = cc.emit(err); - if (!fun) - return NULL; - - // Grab the lock before linking code in, since the watchdog timer will look - // at this list on another thread. - ke::AutoLock lock(Environment::get()->lock()); - - prt->AddJittedFunction(fun); - return fun; -} - -static int -CompileFromThunk(PluginRuntime *runtime, cell_t pcode_offs, void **addrp, char *pc) -{ - // If the watchdog timer has declared a timeout, we must process it now, - // and possibly refuse to compile, since otherwise we will compile a - // function that is not patched for timeouts. - if (!Environment::get()->watchdog()->HandleInterrupt()) - return SP_ERROR_TIMEOUT; - - CompiledFunction *fn = runtime->GetJittedFunctionByOffset(pcode_offs); - if (!fn) { - int err; - fn = CompileFunction(runtime, pcode_offs, &err); - if (!fn) - return err; - } - -#if defined JIT_SPEW - Environment::get()->debugger()->OnDebugSpew( - "Patching thunk to %s::%s\n", - runtime->plugin()->name, - GetFunctionName(runtime->plugin(), pcode_offs)); -#endif - - *addrp = fn->GetEntryAddress(); - - /* Right now, we always keep the code RWE */ - *(intptr_t *)(pc - 4) = intptr_t(fn->GetEntryAddress()) - intptr_t(pc); - return SP_ERROR_NONE; -} - -Compiler::Compiler(PluginRuntime *rt, cell_t pcode_offs) - : env_(Environment::get()), - rt_(rt), - context_(rt->GetBaseContext()), - image_(rt_->image()), - error_(SP_ERROR_NONE), - pcode_start_(pcode_offs), - code_start_(reinterpret_cast(rt_->code().bytes + pcode_start_)), - cip_(code_start_), - code_end_(reinterpret_cast(rt_->code().bytes + rt_->code().length)) -{ - size_t nmaxops = rt_->code().length / sizeof(cell_t) + 1; - jump_map_ = new Label[nmaxops]; -} - -Compiler::~Compiler() -{ - delete [] jump_map_; -} - -CompiledFunction * -Compiler::emit(int *errp) -{ - if (cip_ >= code_end_ || *cip_ != OP_PROC) { - *errp = SP_ERROR_INVALID_INSTRUCTION; - return NULL; - } - -#if defined JIT_SPEW - g_engine1.GetDebugHook()->OnDebugSpew( - "Compiling function %s::%s\n", - rt_->Name(), - GetFunctionName(plugin_, pcode_start_)); - - SpewOpcode(plugin_, code_start_, cip_); -#endif - - const cell_t *codeseg = reinterpret_cast(rt_->code().bytes); - - cip_++; - if (!emitOp(OP_PROC)) { - *errp = (error_ == SP_ERROR_NONE) ? SP_ERROR_OUT_OF_MEMORY : error_; - return NULL; - } - - while (cip_ < code_end_) { - // If we reach the end of this function, or the beginning of a new - // procedure, then stop. - if (*cip_ == OP_PROC || *cip_ == OP_ENDPROC) - break; - -#if defined JIT_SPEW - SpewOpcode(plugin_, code_start_, cip_); -#endif - - // We assume every instruction is a jump target, so before emitting - // an opcode, we bind its corresponding label. - __ bind(&jump_map_[cip_ - codeseg]); - - // Save the start of the opcode for emitCipMap(). - op_cip_ = cip_; - - OPCODE op = (OPCODE)readCell(); - if (!emitOp(op) || error_ != SP_ERROR_NONE) { - *errp = (error_ == SP_ERROR_NONE) ? SP_ERROR_OUT_OF_MEMORY : error_; - return NULL; - } - } - - emitCallThunks(); - - // For each backward jump, emit a little thunk so we can exit from a timeout. - // Track the offset of where the thunk is, so the watchdog timer can patch it. - for (size_t i = 0; i < backward_jumps_.length(); i++) { - BackwardJump &jump = backward_jumps_[i]; - jump.timeout_offset = masm.pc(); - __ call(&throw_timeout_); - emitCipMapping(jump.cip); - } - - // This has to come last. - emitErrorPaths(); - - uint8_t *code = LinkCode(env_, masm); - if (!code) { - *errp = SP_ERROR_OUT_OF_MEMORY; - return NULL; - } - - AutoPtr> edges( - new FixedArray(backward_jumps_.length())); - for (size_t i = 0; i < backward_jumps_.length(); i++) { - const BackwardJump &jump = backward_jumps_[i]; - edges->at(i).offset = jump.pc; - edges->at(i).disp32 = int32_t(jump.timeout_offset) - int32_t(jump.pc); - } - - AutoPtr> cipmap( - new FixedArray(cip_map_.length())); - memcpy(cipmap->buffer(), cip_map_.buffer(), cip_map_.length() * sizeof(CipMapEntry)); - - return new CompiledFunction(code, masm.length(), pcode_start_, edges.take(), cipmap.take()); -} - -// No exit frame - error code is returned directly. -static int -InvokePushTracker(PluginContext *cx, uint32_t amount) -{ - return cx->pushTracker(amount); -} - -// No exit frame - error code is returned directly. -static int -InvokePopTrackerAndSetHeap(PluginContext *cx) -{ - return cx->popTrackerAndSetHeap(); -} - -// Error code must be checked in the environment. -static cell_t -InvokeNativeHelper(PluginContext *cx, ucell_t native_idx, cell_t *params) -{ - return cx->invokeNative(native_idx, params); -} - -// Error code must be checked in the environment. -static cell_t -InvokeBoundNativeHelper(PluginContext *cx, SPVM_NATIVE_FUNC fn, cell_t *params) -{ - return cx->invokeBoundNative(fn, params); -} - -// No exit frame - error code is returned directly. -static int -InvokeGenerateFullArray(PluginContext *cx, uint32_t argc, cell_t *argv, int autozero) -{ - return cx->generateFullArray(argc, argv, autozero); -} - -// Exit frame is a JitExitFrameForHelper. -static void -InvokeReportError(int err) -{ - Environment::get()->ReportError(err); -} - -// Exit frame is a JitExitFrameForHelper. This is a special function since we -// have to notify the watchdog timer that we're unblocked. -static void -InvokeReportTimeout() -{ - Environment::get()->watchdog()->NotifyTimeoutReceived(); - InvokeReportError(SP_ERROR_TIMEOUT); -} - -bool -Compiler::emitOp(OPCODE op) -{ - switch (op) { - case OP_MOVE_PRI: - __ movl(pri, alt); - break; - - case OP_MOVE_ALT: - __ movl(alt, pri); - break; - - case OP_XCHG: - __ xchgl(pri, alt); - break; - - case OP_ZERO: - { - cell_t offset = readCell(); - __ movl(Operand(dat, offset), 0); - break; - } - - case OP_ZERO_S: - { - cell_t offset = readCell(); - __ movl(Operand(frm, offset), 0); - break; - } - - case OP_PUSH_PRI: - case OP_PUSH_ALT: - { - Register reg = (op == OP_PUSH_PRI) ? pri : alt; - __ movl(Operand(stk, -4), reg); - __ subl(stk, 4); - break; - } - - case OP_PUSH_C: - case OP_PUSH2_C: - case OP_PUSH3_C: - case OP_PUSH4_C: - case OP_PUSH5_C: - { - int n = 1; - if (op >= OP_PUSH2_C) - n = ((op - OP_PUSH2_C) / 4) + 2; - - int i = 1; - do { - cell_t val = readCell(); - __ movl(Operand(stk, -(4 * i)), val); - } while (i++ < n); - __ subl(stk, 4 * n); - break; - } - - case OP_PUSH_ADR: - case OP_PUSH2_ADR: - case OP_PUSH3_ADR: - case OP_PUSH4_ADR: - case OP_PUSH5_ADR: - { - int n = 1; - if (op >= OP_PUSH2_ADR) - n = ((op - OP_PUSH2_ADR) / 4) + 2; - - int i = 1; - - // We temporarily relocate FRM to be a local address instead of an - // absolute address. - __ subl(frm, dat); - do { - cell_t offset = readCell(); - __ lea(tmp, Operand(frm, offset)); - __ movl(Operand(stk, -(4 * i)), tmp); - } while (i++ < n); - __ subl(stk, 4 * n); - __ addl(frm, dat); - break; - } - - case OP_PUSH_S: - case OP_PUSH2_S: - case OP_PUSH3_S: - case OP_PUSH4_S: - case OP_PUSH5_S: - { - int n = 1; - if (op >= OP_PUSH2_S) - n = ((op - OP_PUSH2_S) / 4) + 2; - - int i = 1; - do { - cell_t offset = readCell(); - __ movl(tmp, Operand(frm, offset)); - __ movl(Operand(stk, -(4 * i)), tmp); - } while (i++ < n); - __ subl(stk, 4 * n); - break; - } - - case OP_PUSH: - case OP_PUSH2: - case OP_PUSH3: - case OP_PUSH4: - case OP_PUSH5: - { - int n = 1; - if (op >= OP_PUSH2) - n = ((op - OP_PUSH2) / 4) + 2; - - int i = 1; - do { - cell_t offset = readCell(); - __ movl(tmp, Operand(dat, offset)); - __ movl(Operand(stk, -(4 * i)), tmp); - } while (i++ < n); - __ subl(stk, 4 * n); - break; - } - - case OP_ZERO_PRI: - __ xorl(pri, pri); - break; - - case OP_ZERO_ALT: - __ xorl(alt, alt); - break; - - case OP_ADD: - __ addl(pri, alt); - break; - - case OP_SUB: - __ subl(pri, alt); - break; - - case OP_SUB_ALT: - __ movl(tmp, alt); - __ subl(tmp, pri); - __ movl(pri, tmp); - break; - - case OP_PROC: - // Push the old frame onto the stack. - __ movl(tmp, Operand(frmAddr())); - __ movl(Operand(stk, -4), tmp); - __ subl(stk, 8); // extra unused slot for non-existant CIP - - // Get and store the new frame. - __ movl(tmp, stk); - __ movl(frm, stk); - __ subl(tmp, dat); - __ movl(Operand(frmAddr()), tmp); - - // Store the function cip for stack traces. - __ push(pcode_start_); - - // Align the stack to 16-bytes (each call adds 8 bytes). - __ subl(esp, 8); -#if defined(DEBUG) - // Debug guards. - __ movl(Operand(esp, 0), 0xffaaee00); - __ movl(Operand(esp, 4), 0xffaaee04); -#endif - break; - - case OP_IDXADDR_B: - { - cell_t val = readCell(); - __ shll(pri, val); - __ addl(pri, alt); - break; - } - - case OP_SHL: - __ movl(ecx, alt); - __ shll_cl(pri); - break; - - case OP_SHR: - __ movl(ecx, alt); - __ shrl_cl(pri); - break; - - case OP_SSHR: - __ movl(ecx, alt); - __ sarl_cl(pri); - break; - - case OP_SHL_C_PRI: - case OP_SHL_C_ALT: - { - Register reg = (op == OP_SHL_C_PRI) ? pri : alt; - cell_t val = readCell(); - __ shll(reg, val); - break; - } - - case OP_SHR_C_PRI: - case OP_SHR_C_ALT: - { - Register reg = (op == OP_SHR_C_PRI) ? pri : alt; - cell_t val = readCell(); - __ shrl(reg, val); - break; - } - - case OP_SMUL: - __ imull(pri, alt); - break; - - case OP_NOT: - __ testl(eax, eax); - __ movl(eax, 0); - __ set(zero, r8_al); - break; - - case OP_NEG: - __ negl(eax); - break; - - case OP_XOR: - __ xorl(pri, alt); - break; - - case OP_OR: - __ orl(pri, alt); - break; - - case OP_AND: - __ andl(pri, alt); - break; - - case OP_INVERT: - __ notl(pri); - break; - - case OP_ADD_C: - { - cell_t val = readCell(); - __ addl(pri, val); - break; - } - - case OP_SMUL_C: - { - cell_t val = readCell(); - __ imull(pri, pri, val); - break; - } - - case OP_EQ: - case OP_NEQ: - case OP_SLESS: - case OP_SLEQ: - case OP_SGRTR: - case OP_SGEQ: - { - ConditionCode cc = OpToCondition(op); - __ cmpl(pri, alt); - __ movl(pri, 0); - __ set(cc, r8_al); - break; - } - - case OP_EQ_C_PRI: - case OP_EQ_C_ALT: - { - Register reg = (op == OP_EQ_C_PRI) ? pri : alt; - cell_t val = readCell(); - __ cmpl(reg, val); - __ movl(pri, 0); - __ set(equal, r8_al); - break; - } - - case OP_INC_PRI: - case OP_INC_ALT: - { - Register reg = (OP_INC_PRI) ? pri : alt; - __ addl(reg, 1); - break; - } - - case OP_INC: - case OP_INC_S: - { - Register base = (op == OP_INC) ? dat : frm; - cell_t offset = readCell(); - __ addl(Operand(base, offset), 1); - break; - } - - case OP_INC_I: - __ addl(Operand(dat, pri, NoScale), 1); - break; - - case OP_DEC_PRI: - case OP_DEC_ALT: - { - Register reg = (op == OP_DEC_PRI) ? pri : alt; - __ subl(reg, 1); - break; - } - - case OP_DEC: - case OP_DEC_S: - { - Register base = (op == OP_DEC) ? dat : frm; - cell_t offset = readCell(); - __ subl(Operand(base, offset), 1); - break; - } - - case OP_DEC_I: - __ subl(Operand(dat, pri, NoScale), 1); - break; - - case OP_LOAD_PRI: - case OP_LOAD_ALT: - { - Register reg = (op == OP_LOAD_PRI) ? pri : alt; - cell_t offset = readCell(); - __ movl(reg, Operand(dat, offset)); - break; - } - - case OP_LOAD_BOTH: - { - cell_t offs1 = readCell(); - cell_t offs2 = readCell(); - __ movl(pri, Operand(dat, offs1)); - __ movl(alt, Operand(dat, offs2)); - break; - } - - case OP_LOAD_S_PRI: - case OP_LOAD_S_ALT: - { - Register reg = (op == OP_LOAD_S_PRI) ? pri : alt; - cell_t offset = readCell(); - __ movl(reg, Operand(frm, offset)); - break; - } - - case OP_LOAD_S_BOTH: - { - cell_t offs1 = readCell(); - cell_t offs2 = readCell(); - __ movl(pri, Operand(frm, offs1)); - __ movl(alt, Operand(frm, offs2)); - break; - } - - case OP_LREF_S_PRI: - case OP_LREF_S_ALT: - { - Register reg = (op == OP_LREF_S_PRI) ? pri : alt; - cell_t offset = readCell(); - __ movl(reg, Operand(frm, offset)); - __ movl(reg, Operand(dat, reg, NoScale)); - break; - } - - case OP_CONST_PRI: - case OP_CONST_ALT: - { - Register reg = (op == OP_CONST_PRI) ? pri : alt; - cell_t val = readCell(); - __ movl(reg, val); - break; - } - - case OP_ADDR_PRI: - case OP_ADDR_ALT: - { - Register reg = (op == OP_ADDR_PRI) ? pri : alt; - cell_t offset = readCell(); - __ movl(reg, Operand(frmAddr())); - __ addl(reg, offset); - break; - } - - case OP_STOR_PRI: - case OP_STOR_ALT: - { - Register reg = (op == OP_STOR_PRI) ? pri : alt; - cell_t offset = readCell(); - __ movl(Operand(dat, offset), reg); - break; - } - - case OP_STOR_S_PRI: - case OP_STOR_S_ALT: - { - Register reg = (op == OP_STOR_S_PRI) ? pri : alt; - cell_t offset = readCell(); - __ movl(Operand(frm, offset), reg); - break; - } - - case OP_IDXADDR: - __ lea(pri, Operand(alt, pri, ScaleFour)); - break; - - case OP_SREF_S_PRI: - case OP_SREF_S_ALT: - { - Register reg = (op == OP_SREF_S_PRI) ? pri : alt; - cell_t offset = readCell(); - __ movl(tmp, Operand(frm, offset)); - __ movl(Operand(dat, tmp, NoScale), reg); - break; - } - - case OP_POP_PRI: - case OP_POP_ALT: - { - Register reg = (op == OP_POP_PRI) ? pri : alt; - __ movl(reg, Operand(stk, 0)); - __ addl(stk, 4); - break; - } - - case OP_SWAP_PRI: - case OP_SWAP_ALT: - { - Register reg = (op == OP_SWAP_PRI) ? pri : alt; - __ movl(tmp, Operand(stk, 0)); - __ movl(Operand(stk, 0), reg); - __ movl(reg, tmp); - break; - } - - case OP_LIDX: - __ lea(pri, Operand(alt, pri, ScaleFour)); - __ movl(pri, Operand(dat, pri, NoScale)); - break; - - case OP_LIDX_B: - { - cell_t val = readCell(); - if (val >= 0 && val <= 3) { - __ lea(pri, Operand(alt, pri, Scale(val))); - } else { - __ shll(pri, val); - __ addl(pri, alt); - } - emitCheckAddress(pri); - __ movl(pri, Operand(dat, pri, NoScale)); - break; - } - - case OP_CONST: - case OP_CONST_S: - { - Register base = (op == OP_CONST) ? dat : frm; - cell_t offset = readCell(); - cell_t val = readCell(); - __ movl(Operand(base, offset), val); - break; - } - - case OP_LOAD_I: - emitCheckAddress(pri); - __ movl(pri, Operand(dat, pri, NoScale)); - break; - - case OP_STOR_I: - emitCheckAddress(alt); - __ movl(Operand(dat, alt, NoScale), pri); - break; - - case OP_SDIV: - case OP_SDIV_ALT: - { - Register dividend = (op == OP_SDIV) ? pri : alt; - Register divisor = (op == OP_SDIV) ? alt : pri; - - // Guard against divide-by-zero. - __ testl(divisor, divisor); - jumpOnError(zero, SP_ERROR_DIVIDE_BY_ZERO); - - // A more subtle case; -INT_MIN / -1 yields an overflow exception. - Label ok; - __ cmpl(divisor, -1); - __ j(not_equal, &ok); - __ cmpl(dividend, 0x80000000); - jumpOnError(equal, SP_ERROR_INTEGER_OVERFLOW); - __ bind(&ok); - - // Now we can actually perform the divide. - __ movl(tmp, divisor); - if (op == OP_SDIV) - __ movl(edx, dividend); - else - __ movl(eax, dividend); - __ sarl(edx, 31); - __ idivl(tmp); - break; - } - - case OP_LODB_I: - { - cell_t val = readCell(); - emitCheckAddress(pri); - __ movl(pri, Operand(dat, pri, NoScale)); - if (val == 1) - __ andl(pri, 0xff); - else if (val == 2) - __ andl(pri, 0xffff); - break; - } - - case OP_STRB_I: - { - cell_t val = readCell(); - emitCheckAddress(alt); - if (val == 1) - __ movb(Operand(dat, alt, NoScale), pri); - else if (val == 2) - __ movw(Operand(dat, alt, NoScale), pri); - else if (val == 4) - __ movl(Operand(dat, alt, NoScale), pri); - break; - } - - case OP_RETN: - { - // Restore the old frame pointer. - __ movl(frm, Operand(stk, 4)); // get the old frm - __ addl(stk, 8); // pop stack - __ movl(Operand(frmAddr()), frm); // store back old frm - __ addl(frm, dat); // relocate - - // Remove parameters. - __ movl(tmp, Operand(stk, 0)); - __ lea(stk, Operand(stk, tmp, ScaleFour, 4)); - __ addl(esp, 12); - __ ret(); - break; - } - - case OP_MOVS: - { - cell_t val = readCell(); - unsigned dwords = val / 4; - unsigned bytes = val % 4; - - __ cld(); - __ push(esi); - __ push(edi); - // Note: set edi first, since we need esi. - __ lea(edi, Operand(dat, alt, NoScale)); - __ lea(esi, Operand(dat, pri, NoScale)); - if (dwords) { - __ movl(ecx, dwords); - __ rep_movsd(); - } - if (bytes) { - __ movl(ecx, bytes); - __ rep_movsb(); - } - __ pop(edi); - __ pop(esi); - break; - } - - case OP_FILL: - { - // eax/pri is used implicitly. - unsigned dwords = readCell() / 4; - __ push(edi); - __ lea(edi, Operand(dat, alt, NoScale)); - __ movl(ecx, dwords); - __ cld(); - __ rep_stosd(); - __ pop(edi); - break; - } - - case OP_STRADJUST_PRI: - __ addl(pri, 4); - __ sarl(pri, 2); - break; - - case OP_FABS: - __ movl(pri, Operand(stk, 0)); - __ andl(pri, 0x7fffffff); - __ addl(stk, 4); - break; - - case OP_FLOAT: - if (MacroAssemblerX86::Features().sse2) { - __ cvtsi2ss(xmm0, Operand(edi, 0)); - __ movd(pri, xmm0); - } else { - __ fild32(Operand(edi, 0)); - __ subl(esp, 4); - __ fstp32(Operand(esp, 0)); - __ pop(pri); - } - __ addl(stk, 4); - break; - - case OP_FLOATADD: - case OP_FLOATSUB: - case OP_FLOATMUL: - case OP_FLOATDIV: - if (MacroAssemblerX86::Features().sse2) { - __ movss(xmm0, Operand(stk, 0)); - if (op == OP_FLOATADD) - __ addss(xmm0, Operand(stk, 4)); - else if (op == OP_FLOATSUB) - __ subss(xmm0, Operand(stk, 4)); - else if (op == OP_FLOATMUL) - __ mulss(xmm0, Operand(stk, 4)); - else if (op == OP_FLOATDIV) - __ divss(xmm0, Operand(stk, 4)); - __ movd(pri, xmm0); - } else { - __ subl(esp, 4); - __ fld32(Operand(stk, 0)); - - if (op == OP_FLOATADD) - __ fadd32(Operand(stk, 4)); - else if (op == OP_FLOATSUB) - __ fsub32(Operand(stk, 4)); - else if (op == OP_FLOATMUL) - __ fmul32(Operand(stk, 4)); - else if (op == OP_FLOATDIV) - __ fdiv32(Operand(stk, 4)); - - __ fstp32(Operand(esp, 0)); - __ pop(pri); - } - __ addl(stk, 8); - break; - - case OP_RND_TO_NEAREST: - { - if (MacroAssemblerX86::Features().sse) { - // Assume no one is touching MXCSR. - __ cvtss2si(pri, Operand(stk, 0)); - } else { - static float kRoundToNearest = 0.5f; - // From http://wurstcaptures.untergrund.net/assembler_tricks.html#fastfloorf - __ fld32(Operand(stk, 0)); - __ fadd32(st0, st0); - __ fadd32(Operand(ExternalAddress(&kRoundToNearest))); - __ subl(esp, 4); - __ fistp32(Operand(esp, 0)); - __ pop(pri); - __ sarl(pri, 1); - } - __ addl(stk, 4); - break; - } - - case OP_RND_TO_CEIL: - { - static float kRoundToCeil = -0.5f; - // From http://wurstcaptures.untergrund.net/assembler_tricks.html#fastfloorf - __ fld32(Operand(stk, 0)); - __ fadd32(st0, st0); - __ fsubr32(Operand(ExternalAddress(&kRoundToCeil))); - __ subl(esp, 4); - __ fistp32(Operand(esp, 0)); - __ pop(pri); - __ sarl(pri, 1); - __ negl(pri); - __ addl(stk, 4); - break; - } - - case OP_RND_TO_ZERO: - if (MacroAssemblerX86::Features().sse) { - __ cvttss2si(pri, Operand(stk, 0)); - } else { - __ fld32(Operand(stk, 0)); - __ subl(esp, 8); - __ fstcw(Operand(esp, 4)); - __ movl(Operand(esp, 0), 0xfff); - __ fldcw(Operand(esp, 0)); - __ fistp32(Operand(esp, 0)); - __ pop(pri); - __ fldcw(Operand(esp, 0)); - __ addl(esp, 4); - } - __ addl(stk, 4); - break; - - case OP_RND_TO_FLOOR: - __ fld32(Operand(stk, 0)); - __ subl(esp, 8); - __ fstcw(Operand(esp, 4)); - __ movl(Operand(esp, 0), 0x7ff); - __ fldcw(Operand(esp, 0)); - __ fistp32(Operand(esp, 0)); - __ pop(eax); - __ fldcw(Operand(esp, 0)); - __ addl(esp, 4); - __ addl(stk, 4); - break; - - // This is the old float cmp, which returns ordered results. In newly - // compiled code it should not be used or generated. - // - // Note that the checks here are inverted: the test is |rhs OP lhs|. - case OP_FLOATCMP: - { - Label bl, ab, done; - if (MacroAssemblerX86::Features().sse) { - __ movss(xmm0, Operand(stk, 4)); - __ ucomiss(Operand(stk, 0), xmm0); - } else { - __ fld32(Operand(stk, 0)); - __ fld32(Operand(stk, 4)); - __ fucomip(st1); - __ fstp(st0); - } - __ j(above, &ab); - __ j(below, &bl); - __ xorl(pri, pri); - __ jmp(&done); - __ bind(&ab); - __ movl(pri, -1); - __ jmp(&done); - __ bind(&bl); - __ movl(pri, 1); - __ bind(&done); - __ addl(stk, 8); - break; - } - - case OP_FLOAT_GT: - emitFloatCmp(above); - break; - - case OP_FLOAT_GE: - emitFloatCmp(above_equal); - break; - - case OP_FLOAT_LE: - emitFloatCmp(below_equal); - break; - - case OP_FLOAT_LT: - emitFloatCmp(below); - break; - - case OP_FLOAT_EQ: - emitFloatCmp(equal); - break; - - case OP_FLOAT_NE: - emitFloatCmp(not_equal); - break; - - case OP_FLOAT_NOT: - { - if (MacroAssemblerX86::Features().sse) { - __ xorps(xmm0, xmm0); - __ ucomiss(Operand(stk, 0), xmm0); - } else { - __ fld32(Operand(stk, 0)); - __ fldz(); - __ fucomip(st1); - __ fstp(st0); - } - - // See emitFloatCmp() - this is a shorter version. - Label done; - __ movl(eax, 1); - __ j(parity, &done); - __ set(zero, r8_al); - __ bind(&done); - - __ addl(stk, 4); - break; - } - - case OP_STACK: - { - cell_t amount = readCell(); - __ addl(stk, amount); - - if (amount > 0) { - // Check if the stack went beyond the stack top - usually a compiler error. - __ cmpl(stk, intptr_t(context_->memory() + context_->HeapSize())); - jumpOnError(not_below, SP_ERROR_STACKMIN); - } else { - // Check if the stack is going to collide with the heap. - __ movl(tmp, Operand(hpAddr())); - __ lea(tmp, Operand(dat, ecx, NoScale, STACK_MARGIN)); - __ cmpl(stk, tmp); - jumpOnError(below, SP_ERROR_STACKLOW); - } - break; - } - - case OP_HEAP: - { - cell_t amount = readCell(); - __ movl(alt, Operand(hpAddr())); - __ addl(Operand(hpAddr()), amount); - - if (amount < 0) { - __ cmpl(Operand(hpAddr()), context_->DataSize()); - jumpOnError(below, SP_ERROR_HEAPMIN); - } else { - __ movl(tmp, Operand(hpAddr())); - __ lea(tmp, Operand(dat, ecx, NoScale, STACK_MARGIN)); - __ cmpl(tmp, stk); - jumpOnError(above, SP_ERROR_HEAPLOW); - } - break; - } - - case OP_JUMP: - { - Label *target = labelAt(readCell()); - if (!target) - return false; - if (target->bound()) { - __ jmp32(target); - backward_jumps_.append(BackwardJump(masm.pc(), op_cip_)); - } else { - __ jmp(target); - } - break; - } - - case OP_JZER: - case OP_JNZ: - { - ConditionCode cc = (op == OP_JZER) ? zero : not_zero; - Label *target = labelAt(readCell()); - if (!target) - return false; - __ testl(pri, pri); - if (target->bound()) { - __ j32(cc, target); - backward_jumps_.append(BackwardJump(masm.pc(), op_cip_)); - } else { - __ j(cc, target); - } - break; - } - - case OP_JEQ: - case OP_JNEQ: - case OP_JSLESS: - case OP_JSLEQ: - case OP_JSGRTR: - case OP_JSGEQ: - { - Label *target = labelAt(readCell()); - if (!target) - return false; - ConditionCode cc = OpToCondition(op); - __ cmpl(pri, alt); - if (target->bound()) { - __ j32(cc, target); - backward_jumps_.append(BackwardJump(masm.pc(), op_cip_)); - } else { - __ j(cc, target); - } - break; - } - - case OP_TRACKER_PUSH_C: - { - cell_t amount = readCell(); - - __ push(pri); - __ push(alt); - - __ push(amount * 4); - __ push(intptr_t(rt_->GetBaseContext())); - __ call(ExternalAddress((void *)InvokePushTracker)); - __ addl(esp, 8); - __ testl(eax, eax); - jumpOnError(not_zero); - - __ pop(alt); - __ pop(pri); - break; - } - - case OP_TRACKER_POP_SETHEAP: - { - // Save registers. - __ push(pri); - __ push(alt); - - // Get the context pointer and call the sanity checker. - __ push(intptr_t(rt_->GetBaseContext())); - __ call(ExternalAddress((void *)InvokePopTrackerAndSetHeap)); - __ addl(esp, 4); - __ testl(eax, eax); - jumpOnError(not_zero); - - __ pop(alt); - __ pop(pri); - break; - } - - // This opcode is used to note where line breaks occur. We don't support - // live debugging, and if we did, we could build this map from the lines - // table. So we don't generate any code here. - case OP_BREAK: - break; - - // This should never be hit. - case OP_HALT: - __ align(16); - __ movl(pri, readCell()); - __ testl(eax, eax); - jumpOnError(not_zero); - break; - - case OP_BOUNDS: - { - cell_t value = readCell(); - __ cmpl(eax, value); - jumpOnError(above, SP_ERROR_ARRAY_BOUNDS); - break; - } - - case OP_GENARRAY: - case OP_GENARRAY_Z: - emitGenArray(op == OP_GENARRAY_Z); - break; - - case OP_CALL: - if (!emitCall()) - return false; - break; - - case OP_SYSREQ_C: - case OP_SYSREQ_N: - if (!emitNativeCall(op)) - return false; - break; - - case OP_SWITCH: - if (!emitSwitch()) - return false; - break; - - case OP_CASETBL: - { - size_t ncases = readCell(); - - // Two cells per case, and one extra cell for the default address. - cip_ += (ncases * 2) + 1; - break; - } - - case OP_NOP: - break; - - default: - error_ = SP_ERROR_INVALID_INSTRUCTION; - return false; - } - - return true; -} - -Label * -Compiler::labelAt(size_t offset) -{ - if (offset % 4 != 0 || - offset > rt_->code().length || - offset <= pcode_start_) - { - // If the jump target is misaligned, or out of pcode bounds, or is an - // address out of the function bounds, we abort. Unfortunately we can't - // test beyond the end of the function since we don't have a precursor - // pass (yet). - error_ = SP_ERROR_INSTRUCTION_PARAM; - return NULL; - } - - return &jump_map_[offset / sizeof(cell_t)]; -} - -void -Compiler::emitCheckAddress(Register reg) -{ - // Check if we're in memory bounds. - __ cmpl(reg, context_->HeapSize()); - jumpOnError(not_below, SP_ERROR_MEMACCESS); - - // Check if we're in the invalid region between hp and sp. - Label done; - __ cmpl(reg, Operand(hpAddr())); - __ j(below, &done); - __ lea(tmp, Operand(dat, reg, NoScale)); - __ cmpl(tmp, stk); - jumpOnError(below, SP_ERROR_MEMACCESS); - __ bind(&done); -} - -void -Compiler::emitGenArray(bool autozero) -{ - cell_t val = readCell(); - if (val == 1) - { - // flat array; we can generate this without indirection tables. - // Note that we can overwrite ALT because technically STACK should be destroying ALT - __ movl(alt, Operand(hpAddr())); - __ movl(tmp, Operand(stk, 0)); - __ movl(Operand(stk, 0), alt); // store base of the array into the stack. - __ lea(alt, Operand(alt, tmp, ScaleFour)); - __ movl(Operand(hpAddr()), alt); - __ addl(alt, dat); - __ cmpl(alt, stk); - jumpOnError(not_below, SP_ERROR_HEAPLOW); - - __ shll(tmp, 2); - __ push(tmp); - __ push(intptr_t(rt_->GetBaseContext())); - __ call(ExternalAddress((void *)InvokePushTracker)); - __ addl(esp, 4); - __ pop(tmp); - __ shrl(tmp, 2); - __ testl(eax, eax); - jumpOnError(not_zero); - - if (autozero) { - // Note - tmp is ecx and still intact. - __ push(eax); - __ push(edi); - __ xorl(eax, eax); - __ movl(edi, Operand(stk, 0)); - __ addl(edi, dat); - __ cld(); - __ rep_stosd(); - __ pop(edi); - __ pop(eax); - } - } else { - __ push(pri); - - // int GenerateArray(cx, vars[], uint32_t, cell_t *, int, unsigned *); - __ push(autozero ? 1 : 0); - __ push(stk); - __ push(val); - __ push(intptr_t(context_)); - __ call(ExternalAddress((void *)InvokeGenerateFullArray)); - __ addl(esp, 4 * sizeof(void *)); - - // restore pri to tmp - __ pop(tmp); - - __ testl(eax, eax); - jumpOnError(not_zero); - - // Move tmp back to pri, remove pushed args. - __ movl(pri, tmp); - __ addl(stk, (val - 1) * 4); - } -} - -bool -Compiler::emitCall() -{ - cell_t offset = readCell(); - - // If this offset looks crappy, i.e. not aligned or out of bounds, we just - // abort. - if (offset % 4 != 0 || uint32_t(offset) >= rt_->code().length) { - error_ = SP_ERROR_INSTRUCTION_PARAM; - return false; - } - - CompiledFunction *fun = rt_->GetJittedFunctionByOffset(offset); - if (!fun) { - // Need to emit a delayed thunk. - CallThunk *thunk = new CallThunk(offset); - __ call(&thunk->call); - if (!thunks_.append(thunk)) - return false; - } else { - // Function is already emitted, we can do a direct call. - __ call(ExternalAddress(fun->GetEntryAddress())); - } - - // Map the return address to the cip that started this call. - emitCipMapping(op_cip_); - return true; -} - -void -Compiler::emitCallThunks() -{ - for (size_t i = 0; i < thunks_.length(); i++) { - CallThunk *thunk = thunks_[i]; - - Label error; - __ bind(&thunk->call); - - // Get the return address, since that is the call that we need to patch. - __ movl(eax, Operand(esp, 0)); - - // Push an OP_PROC frame as if we already called the function. This helps - // error reporting. - __ push(thunk->pcode_offset); - __ subl(esp, 8); - - // Create the exit frame, then align the stack. - __ push(0); - __ movl(ecx, intptr_t(&Environment::get()->exit_frame())); - __ movl(Operand(ecx, ExitFrame::offsetOfExitNative()), -1); - __ movl(Operand(ecx, ExitFrame::offsetOfExitSp()), esp); - - // We need to push 4 arguments, and one of them will need an extra word - // on the stack. Allocate a big block so we're aligned. - // - // Note: we add 12 since the push above misaligned the stack. - static const size_t kStackNeeded = 5 * sizeof(void *); - static const size_t kStackReserve = ke::Align(kStackNeeded, 16) + 3 * sizeof(void *); - __ subl(esp, kStackReserve); - - // Set arguments. - __ movl(Operand(esp, 3 * sizeof(void *)), eax); - __ lea(edx, Operand(esp, 4 * sizeof(void *))); - __ movl(Operand(esp, 2 * sizeof(void *)), edx); - __ movl(Operand(esp, 1 * sizeof(void *)), intptr_t(thunk->pcode_offset)); - __ movl(Operand(esp, 0 * sizeof(void *)), intptr_t(rt_)); - - __ call(ExternalAddress((void *)CompileFromThunk)); - __ movl(edx, Operand(esp, 4 * sizeof(void *))); - __ addl(esp, kStackReserve + 4 * sizeof(void *)); // Drop the exit frame and fake frame. - __ testl(eax, eax); - jumpOnError(not_zero); - __ jmp(edx); - } -} - -cell_t -Compiler::readCell() -{ - if (cip_ >= code_end_) { - error_= SP_ERROR_INVALID_INSTRUCTION; - return 0; - } - return *cip_++; -} - -bool -Compiler::emitNativeCall(OPCODE op) -{ - uint32_t native_index = readCell(); - - if (native_index >= image_->NumNatives()) { - error_ = SP_ERROR_INSTRUCTION_PARAM; - return false; - } - - uint32_t num_params; - if (op == OP_SYSREQ_N) { - num_params = readCell(); - - // See if we can get a replacement opcode. If we can, then recursively - // call emitOp() to generate it. Note: it's important that we do this - // before generating any code for the SYSREQ.N. - unsigned replacement = rt_->GetNativeReplacement(native_index); - if (replacement != OP_NOP) - return emitOp((OPCODE)replacement); - - // Store the number of parameters. - __ movl(Operand(stk, -4), num_params); - __ subl(stk, 4); - } - - // Create the exit frame. This is a JitExitFrameForNative, so everything we - // push up to the return address of the call instruction is reflected in - // that structure. - __ movl(eax, intptr_t(&Environment::get()->exit_frame())); - __ movl(Operand(eax, ExitFrame::offsetOfExitNative()), native_index); - __ movl(Operand(eax, ExitFrame::offsetOfExitSp()), esp); - - // Save registers. - __ push(edx); - - // Push the last parameter for the C++ function. - __ push(stk); - - // Relocate our absolute stk to be dat-relative, and update the context's - // view. - __ subl(stk, dat); - __ movl(eax, intptr_t(context_)); - __ movl(Operand(eax, PluginContext::offsetOfSp()), stk); - - const sp_native_t *native = rt_->GetNative(native_index); - if ((native->status != SP_NATIVE_BOUND) || - (native->flags & (SP_NTVFLAG_OPTIONAL | SP_NTVFLAG_EPHEMERAL))) - { - // The native is either unbound, or it could become unbound in the - // future. Invoke the slower native callback. - __ push(native_index); - __ push(intptr_t(rt_->GetBaseContext())); - __ call(ExternalAddress((void *)InvokeNativeHelper)); - } else { - // The native is bound so we have a few more guarantees. - __ push(intptr_t(native->pfn)); - __ push(intptr_t(rt_->GetBaseContext())); - __ call(ExternalAddress((void *)InvokeBoundNativeHelper)); - } - - // Map the return address to the cip that initiated this call. - emitCipMapping(op_cip_); - - // Check for errors. Note we jump directly to the return stub since the - // error has already been reported. - __ movl(ecx, intptr_t(Environment::get())); - __ cmpl(Operand(ecx, Environment::offsetOfExceptionCode()), 0); - __ j(not_zero, &return_reported_error_); - - // Restore local state. - __ addl(stk, dat); - __ addl(esp, 12); - __ pop(edx); - - if (op == OP_SYSREQ_N) { - // Pop the stack. Do not check the margins. - __ addl(stk, (num_params + 1) * sizeof(cell_t)); - } - return true; -} - -bool -Compiler::emitSwitch() -{ - cell_t offset = readCell(); - if (!labelAt(offset)) - return false; - - cell_t *tbl = (cell_t *)((char *)rt_->code().bytes + offset + sizeof(cell_t)); - - struct Entry { - cell_t val; - cell_t offset; - }; - - size_t ncases = *tbl++; - - Label *defaultCase = labelAt(*tbl); - if (!defaultCase) - return false; - - // Degenerate - 0 cases. - if (!ncases) { - __ jmp(defaultCase); - return true; - } - - Entry *cases = (Entry *)(tbl + 1); - - // Degenerate - 1 case. - if (ncases == 1) { - Label *maybe = labelAt(cases[0].offset); - if (!maybe) - return false; - __ cmpl(pri, cases[0].val); - __ j(equal, maybe); - __ jmp(defaultCase); - return true; - } - - // We have two or more cases, so let's generate a full switch. Decide - // whether we'll make an if chain, or a jump table, based on whether - // the numbers are strictly sequential. - bool sequential = true; - { - cell_t first = cases[0].val; - cell_t last = first; - for (size_t i = 1; i < ncases; i++) { - if (cases[i].val != ++last) { - sequential = false; - break; - } - } - } - - // First check whether the bounds are correct: if (a < LOW || a > HIGH); - // this check is valid whether or not we emit a sequential-optimized switch. - cell_t low = cases[0].val; - if (low != 0) { - // negate it so we'll get a lower bound of 0. - low = -low; - __ lea(tmp, Operand(pri, low)); - } else { - __ movl(tmp, pri); - } - - cell_t high = abs(cases[0].val - cases[ncases - 1].val); - __ cmpl(tmp, high); - __ j(above, defaultCase); - - if (sequential) { - // Optimized table version. The tomfoolery below is because we only have - // one free register... it seems unlikely pri or alt will be used given - // that we're at the end of a control-flow point, but we'll play it safe. - DataLabel table; - __ push(eax); - __ movl(eax, &table); - __ movl(ecx, Operand(eax, ecx, ScaleFour)); - __ pop(eax); - __ jmp(ecx); - - __ bind(&table); - for (size_t i = 0; i < ncases; i++) { - Label *label = labelAt(cases[i].offset); - if (!label) - return false; - __ emit_absolute_address(label); - } - } else { - // Slower version. Go through each case and generate a check. - for (size_t i = 0; i < ncases; i++) { - Label *label = labelAt(cases[i].offset); - if (!label) - return false; - __ cmpl(pri, cases[i].val); - __ j(equal, label); - } - __ jmp(defaultCase); - } - return true; -} - -void -Compiler::emitFloatCmp(ConditionCode cc) -{ - unsigned lhs = 4; - unsigned rhs = 0; - if (cc == below || cc == below_equal) { - // NaN results in ZF=1 PF=1 CF=1 - // - // ja/jae check for ZF,CF=0 and CF=0. If we make all relational compares - // look like ja/jae, we'll guarantee all NaN comparisons will fail (which - // would not be true for jb/jbe, unless we checked with jp). - if (cc == below) - cc = above; - else - cc = above_equal; - rhs = 4; - lhs = 0; - } - - if (MacroAssemblerX86::Features().sse) { - __ movss(xmm0, Operand(stk, rhs)); - __ ucomiss(Operand(stk, lhs), xmm0); - } else { - __ fld32(Operand(stk, rhs)); - __ fld32(Operand(stk, lhs)); - __ fucomip(st1); - __ fstp(st0); - } - - // An equal or not-equal needs special handling for the parity bit. - if (cc == equal || cc == not_equal) { - // If NaN, PF=1, ZF=1, and E/Z tests ZF=1. - // - // If NaN, PF=1, ZF=1 and NE/NZ tests Z=0. But, we want any != with NaNs - // to return true, including NaN != NaN. - // - // To make checks simpler, we set |eax| to the expected value of a NaN - // beforehand. This also clears the top bits of |eax| for setcc. - Label done; - __ movl(eax, (cc == equal) ? 0 : 1); - __ j(parity, &done); - __ set(cc, r8_al); - __ bind(&done); - } else { - __ movl(eax, 0); - __ set(cc, r8_al); - } - __ addl(stk, 8); -} - -void -Compiler::jumpOnError(ConditionCode cc, int err) -{ - // Note: we accept 0 for err. In this case we expect the error to be in eax. - { - ErrorPath path(op_cip_, err); - error_paths_.append(path); - } - - ErrorPath &path = error_paths_.back(); - __ j(cc, &path.label); -} - -void -Compiler::emitErrorPaths() -{ - // For each path that had an error check, bind it to an error routine and - // add it to the cip map. What we'll get is something like: - // - // cmp dividend, 0 - // jz error_thunk_0 - // - // error_thunk_0: - // call integer_overflow - // - // integer_overflow: - // mov eax, SP_ERROR_DIVIDE_BY_ZERO - // jmp report_error - // - // report_error: - // create exit frame - // push eax - // call InvokeReportError(int err) - // - for (size_t i = 0; i < error_paths_.length(); i++) { - ErrorPath &path = error_paths_[i]; - - // If there's no error code, it should be in eax. Otherwise we'll jump to - // a path that sets eax to a hardcoded value. - __ bind(&path.label); - if (path.err == 0) - __ call(&report_error_); - else - __ call(&throw_error_code_[path.err]); - - emitCipMapping(path.cip); - } - - emitThrowPathIfNeeded(SP_ERROR_DIVIDE_BY_ZERO); - emitThrowPathIfNeeded(SP_ERROR_STACKLOW); - emitThrowPathIfNeeded(SP_ERROR_STACKMIN); - emitThrowPathIfNeeded(SP_ERROR_ARRAY_BOUNDS); - emitThrowPathIfNeeded(SP_ERROR_MEMACCESS); - emitThrowPathIfNeeded(SP_ERROR_HEAPLOW); - emitThrowPathIfNeeded(SP_ERROR_HEAPMIN); - emitThrowPathIfNeeded(SP_ERROR_INTEGER_OVERFLOW); - - if (report_error_.used()) { - __ bind(&report_error_); - - // Create the exit frame. We always get here through a call from the opcode - // (and always via an out-of-line thunk). - __ movl(ecx, intptr_t(&Environment::get()->exit_frame())); - __ movl(Operand(ecx, ExitFrame::offsetOfExitNative()), -1); - __ movl(Operand(ecx, ExitFrame::offsetOfExitSp()), esp); - - // Since the return stub wipes out the stack, we don't need to subl after - // the call. - __ push(eax); - __ call(ExternalAddress((void *)InvokeReportError)); - __ jmp(ExternalAddress(env_->stubs()->ReturnStub())); - } - - // We get here if we know an exception is already pending. - if (return_reported_error_.used()) { - __ bind(&return_reported_error_); - __ movl(eax, intptr_t(Environment::get())); - __ movl(eax, Operand(eax, Environment::offsetOfExceptionCode())); - __ jmp(ExternalAddress(env_->stubs()->ReturnStub())); - } - - // The timeout uses a special stub. - if (throw_timeout_.used()) { - __ bind(&throw_timeout_); - - // Create the exit frame. - __ movl(ecx, intptr_t(&Environment::get()->exit_frame())); - __ movl(Operand(ecx, ExitFrame::offsetOfExitNative()), -1); - __ movl(Operand(ecx, ExitFrame::offsetOfExitSp()), esp); - - // Since the return stub wipes out the stack, we don't need to subl after - // the call. - __ call(ExternalAddress((void *)InvokeReportTimeout)); - __ jmp(ExternalAddress(env_->stubs()->ReturnStub())); - } -} - -void -Compiler::emitThrowPathIfNeeded(int err) -{ - assert(err < SP_MAX_ERROR_CODES); - - if (!throw_error_code_[err].used()) - return; - - __ bind(&throw_error_code_[err]); - __ movl(eax, err); - __ jmp(&report_error_); -} diff --git a/sourcepawn/vm/x86/jit_x86.h b/sourcepawn/vm/x86/jit_x86.h deleted file mode 100644 index 33e3fac0..00000000 --- a/sourcepawn/vm/x86/jit_x86.h +++ /dev/null @@ -1,170 +0,0 @@ -// vim: set ts=8 sts=2 sw=2 tw=99 et: -// -// This file is part of SourcePawn. -// -// SourcePawn is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// SourcePawn is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU General Public License -// along with SourcePawn. If not, see . -#ifndef _INCLUDE_SOURCEPAWN_JIT_X86_H_ -#define _INCLUDE_SOURCEPAWN_JIT_X86_H_ - -#include -#include -#include -#include "plugin-runtime.h" -#include "plugin-context.h" -#include "compiled-function.h" -#include "opcodes.h" -#include "macro-assembler-x86.h" - -using namespace SourcePawn; - -namespace sp { -class LegacyImage; -class Environment; -class CompiledFunction; - -struct ErrorPath -{ - SilentLabel label; - const cell_t *cip; - int err; - - ErrorPath(const cell_t *cip, int err) - : cip(cip), - err(err) - {} - ErrorPath() - {} -}; - -struct BackwardJump { - // The pc at the jump instruction (i.e. after it). - uint32_t pc; - // The cip of the jump. - const cell_t *cip; - // The offset of the timeout thunk. This is filled in at the end. - uint32_t timeout_offset; - - BackwardJump() - {} - BackwardJump(uint32_t pc, const cell_t *cip) - : pc(pc), - cip(cip) - {} -}; - -#define JIT_INLINE_ERRORCHECKS (1<<0) -#define JIT_INLINE_NATIVES (1<<1) -#define STACK_MARGIN 64 //8 parameters of safety, I guess -#define JIT_FUNCMAGIC 0x214D4148 //magic function offset - -#define JITVARS_PROFILER 2 //profiler - -#define sDIMEN_MAX 5 //this must mirror what the compiler has. - -struct CallThunk -{ - SilentLabel call; - cell_t pcode_offset; - - CallThunk(cell_t pcode_offset) - : pcode_offset(pcode_offset) - { - } -}; - -class Compiler -{ - public: - Compiler(PluginRuntime *rt, cell_t pcode_offs); - ~Compiler(); - - sp::CompiledFunction *emit(int *errp); - - private: - bool setup(cell_t pcode_offs); - bool emitOp(sp::OPCODE op); - cell_t readCell(); - - private: - Label *labelAt(size_t offset); - bool emitCall(); - bool emitNativeCall(sp::OPCODE op); - bool emitSwitch(); - void emitGenArray(bool autozero); - void emitCallThunks(); - void emitCheckAddress(Register reg); - void emitErrorPath(Label *dest, int code); - void emitErrorPaths(); - void emitFloatCmp(ConditionCode cc); - void jumpOnError(ConditionCode cc, int err = 0); - void emitThrowPathIfNeeded(int err); - - ExternalAddress hpAddr() { - return ExternalAddress(context_->addressOfHp()); - } - ExternalAddress frmAddr() { - return ExternalAddress(context_->addressOfFrm()); - } - - // Map a return address (i.e. an exit point from a function) to its source - // cip. This lets us avoid tracking the cip during runtime. These are - // sorted by definition since we assemble and emit in forward order. - void emitCipMapping(const cell_t *cip) { - CipMapEntry entry; - entry.cipoffs = uintptr_t(cip) - uintptr_t(code_start_); - entry.pcoffs = masm.pc(); - cip_map_.append(entry); - } - - private: - AssemblerX86 masm; - Environment *env_; - PluginRuntime *rt_; - PluginContext *context_; - LegacyImage *image_; - int error_; - uint32_t pcode_start_; - const cell_t *code_start_; - const cell_t *cip_; - const cell_t *op_cip_; - const cell_t *code_end_; - Label *jump_map_; - ke::Vector backward_jumps_; - - ke::Vector cip_map_; - - // Errors. - ke::Vector error_paths_; - Label throw_timeout_; - Label throw_error_code_[SP_MAX_ERROR_CODES]; - Label report_error_; - Label return_reported_error_; - - ke::Vector thunks_; //:TODO: free -}; - -const Register pri = eax; -const Register alt = edx; -const Register stk = edi; -const Register dat = esi; -const Register tmp = ecx; -const Register frm = ebx; - -CompiledFunction * -CompileFunction(PluginRuntime *prt, cell_t pcode_offs, int *err); - -} - -#endif //_INCLUDE_SOURCEPAWN_JIT_X86_H_ - diff --git a/sourcepawn/vm/x86/macro-assembler-x86.h b/sourcepawn/vm/x86/macro-assembler-x86.h deleted file mode 100644 index d664011c..00000000 --- a/sourcepawn/vm/x86/macro-assembler-x86.h +++ /dev/null @@ -1,104 +0,0 @@ -/** - * vim: set ts=8 sts=2 sw=2 tw=99 et: - * ============================================================================= - * SourcePawn JIT SDK - * Copyright (C) 2004-2008 AlliedModders LLC. All rights reserved. - * ============================================================================= - * - * This program is free software; you can redistribute it and/or modify it under - * the terms of the GNU General Public License, version 3.0, as published by the - * Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS - * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more - * details. - * - * You should have received a copy of the GNU General Public License along with - * this program. If not, see . - * - * As a special exception, AlliedModders LLC gives you permission to link the - * code of this program (as well as its derivative works) to "Half-Life 2," the - * "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software - * by the Valve Corporation. You must obey the GNU General Public License in - * all respects for all other code used. Additionally, AlliedModders LLC grants - * this exception to all derivative works. AlliedModders LLC defines further - * exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007), - * or . - * - * Version: $Id$ - */ -#ifndef _include_sourcepawn_macroassembler_x86h__ -#define _include_sourcepawn_macroassembler_x86h__ - -#include -#include -#include -#include "assembler-x86.h" - -class MacroAssemblerX86 : public AssemblerX86 -{ - public: - static void GenerateFeatureDetection(MacroAssemblerX86 &masm) { - masm.push(ebp); - masm.movl(ebp, esp); - masm.push(ebx); - { - // Get ECX, EDX feature bits at the first CPUID level. - masm.movl(eax, 1); - masm.cpuid(); - masm.movl(eax, Operand(ebp, 8)); - masm.movl(Operand(eax, 0), ecx); - masm.movl(eax, Operand(ebp, 12)); - masm.movl(Operand(eax, 0), edx); - } - - // Zero out bits we're not guaranteed to get. - masm.movl(eax, Operand(ebp, 16)); - masm.movl(Operand(eax, 0), 0); - - Label skip_level_7; - { - // Get EBX feature bits at 7th CPUID level. - masm.movl(eax, 0); - masm.cpuid(); - masm.cmpl(eax, 7); - masm.j(below, &skip_level_7); - masm.movl(eax, 7); - masm.movl(ecx, 0); - masm.cpuid(); - masm.movl(eax, Operand(ebp, 16)); - masm.movl(Operand(eax, 0), ebx); - } - masm.bind(&skip_level_7); - - masm.pop(ebx); - masm.pop(ebp); - masm.ret(); - } - - static void RunFeatureDetection(void *code) { - typedef void (*fn_t)(int *reg_ecx, int *reg_edx, int *reg_ebx); - - int reg_ecx, reg_edx, reg_ebx; - ((fn_t)code)(®_ecx, ®_edx, ®_ebx); - - CPUFeatures features; - features.fpu = !!(reg_edx & (1 << 0)); - features.mmx = !!(reg_edx & (1 << 23)); - features.sse = !!(reg_edx & (1 << 25)); - features.sse2 = !!(reg_edx & (1 << 26)); - features.sse3 = !!(reg_ecx & (1 << 0)); - features.ssse3 = !!(reg_ecx & (1 << 9)); - features.sse4_1 = !!(reg_ecx & (1 << 19)); - features.sse4_2 = !!(reg_ecx & (1 << 20)); - features.avx = !!(reg_ecx & (1 << 28)); - features.avx2 = !!(reg_ebx & (1 << 5)); - SetFeatures(features); - } - - private: -}; - -#endif // _include_sourcepawn_macroassembler_x86h__ - diff --git a/sourcepawn/vm/x86/x86-utils.cpp b/sourcepawn/vm/x86/x86-utils.cpp deleted file mode 100644 index 4d73903c..00000000 --- a/sourcepawn/vm/x86/x86-utils.cpp +++ /dev/null @@ -1,30 +0,0 @@ -// vim: set sts=2 ts=8 sw=2 tw=99 et: -// -// Copyright (C) 2006-2015 AlliedModders LLC -// -// This file is part of SourcePawn. SourcePawn is free software: you can -// redistribute it and/or modify it under the terms of the GNU General Public -// License as published by the Free Software Foundation, either version 3 of -// the License, or (at your option) any later version. -// -// You should have received a copy of the GNU General Public License along with -// SourcePawn. If not, see http://www.gnu.org/licenses/. -// -#include "environment.h" -#include "x86-utils.h" - -using namespace sp; - -uint8_t * -sp::LinkCode(Environment *env, AssemblerX86 &masm) -{ - if (masm.outOfMemory()) - return nullptr; - - void *code = env->AllocateCode(masm.length()); - if (!code) - return nullptr; - - masm.emitToExecutableMemory(code); - return reinterpret_cast(code); -} diff --git a/sourcepawn/vm/x86/x86-utils.h b/sourcepawn/vm/x86/x86-utils.h deleted file mode 100644 index e5f40a93..00000000 --- a/sourcepawn/vm/x86/x86-utils.h +++ /dev/null @@ -1,27 +0,0 @@ -// vim: set sts=2 ts=8 sw=2 tw=99 et: -// -// Copyright (C) 2006-2015 AlliedModders LLC -// -// This file is part of SourcePawn. SourcePawn is free software: you can -// redistribute it and/or modify it under the terms of the GNU General Public -// License as published by the Free Software Foundation, either version 3 of -// the License, or (at your option) any later version. -// -// You should have received a copy of the GNU General Public License along with -// SourcePawn. If not, see http://www.gnu.org/licenses/. -// -#ifndef _include_sourcepawn_vm_x86_utils_h_ -#define _include_sourcepawn_vm_x86_utils_h_ - -#include -#include "macro-assembler-x86.h" - -namespace sp { - -class Environment; - -uint8_t *LinkCode(Environment *env, AssemblerX86 &masm); - -} - -#endif // _include_sourcepawn_vm_x86_utils_h_