From 67a5332967fd6297cc70e0645bdc54d40f1a898e Mon Sep 17 00:00:00 2001 From: "Sean T. Allen" Date: Wed, 2 Dec 2026 17:35:45 -0500 Subject: [PATCH] Fix GC bugs with embedded fields and stop tracing constants An embedded field can share its address with the object that holds it, and the GC traced each address as a single type. Because of that, the GC could free a struct's other fields when the struct's first field was embedded, could trace forever around a reference cycle through embedded objects, and could collect an actor while another actor held one of its embedded fields. With a Pointer to the start of a struct, made through FFI, the GC could also free the struct's fields. The runtime now traces a shared address once for each type at it, finds the actor that owns an embedded field, and traces Pointer fields as opaque and with no type. To find the actor that owns an embedded field, the runtime needs to know where the compiler's type descriptors are, so the compiler now places them in a section of their own. It also places its constants in a second section. Nothing writes to a constant at run time, so the GC now skips constants, which makes collection much faster for actors that hold many references to string literals. Closes #6693 Closes #6694 Closes #6695 --- .gitattributes | 1 + .release-notes/next-release.md | 50 + BUILD.md | 4 + CHANGELOG.md | 6 + CMakeLists.txt | 21 + cmake/RunLinkHandoff.cmake | 80 +- cmake/RunNoAllocLink.cmake | 1 + cmake/RunOutputFileLinks.cmake | 17 + src/common/platform.h | 9 + src/common/pony_section_names.h | 27 + src/libponyc/codegen/codegen.c | 92 + src/libponyc/codegen/codegen.h | 15 + src/libponyc/codegen/gencall.c | 13 +- src/libponyc/codegen/gendesc.c | 44 +- src/libponyc/codegen/gendesc.h | 21 + src/libponyc/codegen/genexe.cc | 76 +- src/libponyc/codegen/genfun.c | 12 +- src/libponyc/codegen/genopt.cc | 41 + src/libponyc/codegen/genopt.h | 10 + src/libponyc/codegen/genreference.c | 15 +- src/libponyc/codegen/gentrace.c | 157 +- src/libponyc/codegen/gentrace.h | 3 + src/libponyc/codegen/gentype.c | 183 +- src/libponyc/codegen/gentype.h | 18 + src/libponylto/README.md | 4 +- src/libponylto/heap_to_stack.cc | 10 +- src/libponylto/noalloc_check.cc | 2 + src/libponylto/plugin.cc | 11 +- src/libponyrt/CMakeLists.txt | 1 + src/libponyrt/actor/actor.c | 123 +- src/libponyrt/actor/actor.h | 9 + src/libponyrt/gc/cycle.c | 1 + src/libponyrt/gc/embedflags.h | 21 + src/libponyrt/gc/gc.c | 483 ++++- src/libponyrt/gc/gc.h | 34 + src/libponyrt/gc/marklocal.c | 16 +- src/libponyrt/gc/objectmap.c | 6 +- src/libponyrt/gc/pony_sections.ld | 22 + src/libponyrt/gc/sections.c | 111 + src/libponyrt/gc/sections.h | 93 + src/libponyrt/gc/trace.c | 89 +- src/libponyrt/mem/heap.c | 180 +- src/libponyrt/mem/heap.h | 70 +- src/libponyrt/mem/pagemap.c | 24 +- src/libponyrt/mem/pool.h | 15 + src/libponyrt/mem/pool_arena.c | 128 ++ src/libponyrt/mem/pool_memalign.c | 12 + src/libponyrt/pony.h | 74 +- src/libponyrt/sched/scheduler.c | 4 + src/libponyrt/sched/scheduler.h | 5 + src/libponyrt/sched/start.c | 2 + .../constant-section/expected-exit-code.txt | 1 + .../constant-section/main.pony | 41 + .../constant-section/shim.c | 89 + .../embed-empty-field-address/main.pony | 53 + .../main.pony | 34 + .../main.pony | 34 + .../embed-gc-actor-field-cycle/main.pony | 19 + .../main.pony | 22 + .../main.pony | 47 + .../program-args.txt | 1 + .../embed-gc-actor-struct-start-own/main.pony | 48 + .../main.pony | 78 + .../main.pony | 145 ++ .../program-args.txt | 1 + .../embed-gc-actor-val-field-send/main.pony | 28 + .../embed-gc-class-field-only/main.pony | 42 + .../embed-gc-embedded-field-cycle/main.pony | 35 + .../main.pony | 71 + .../main.pony | 45 + .../main.pony | 58 + .../main.pony | 82 + .../main.pony | 57 + .../main.pony | 70 + .../main.pony | 60 + .../main.pony | 37 + .../main.pony | 36 + .../main.pony | 54 + .../main.pony | 49 + .../main.pony | 45 + .../main.pony | 56 + .../main.pony | 56 + .../main.pony | 34 + .../main.pony | 53 + .../gc-pointer-at-struct-start-send/main.pony | 77 + .../gc-pointer-at-struct-start/main.pony | 53 + test/libponyc/CMakeLists.txt | 2 + test/libponyc/codegen_embed.cc | 806 +++++++ test/libponyc/codegen_optimisation.cc | 31 + test/libponyc/codegen_sections.cc | 135 ++ test/libponyc/noalloc.cc | 37 + test/libponyrt/CMakeLists.txt | 45 + test/libponyrt/gc/embed.cc | 1926 +++++++++++++++++ test/libponyrt/gc/marklocal.cc | 69 +- test/libponyrt/gc/sections.cc | 218 ++ test/libponyrt/gc/test_sections.h | 17 + test/libponyrt/gc/test_type.h | 20 + test/libponyrt/mem/heap.cc | 2 +- test/libponyrt/mem/pool.cc | 103 + test/libponyrt/noscript/noscript.c | 25 + test/noalloc-link/rejected/main.pony | 11 + 101 files changed, 7356 insertions(+), 268 deletions(-) create mode 100644 src/common/pony_section_names.h create mode 100644 src/libponyrt/gc/embedflags.h create mode 100644 src/libponyrt/gc/pony_sections.ld create mode 100644 src/libponyrt/gc/sections.c create mode 100644 src/libponyrt/gc/sections.h create mode 100644 test/full-program-tests/constant-section/expected-exit-code.txt create mode 100644 test/full-program-tests/constant-section/main.pony create mode 100644 test/full-program-tests/constant-section/shim.c create mode 100644 test/full-program-tests/embed-empty-field-address/main.pony create mode 100644 test/full-program-tests/embed-gc-acquire-embedded-struct-forward/main.pony create mode 100644 test/full-program-tests/embed-gc-acquire-embedded-struct-hold/main.pony create mode 100644 test/full-program-tests/embed-gc-actor-field-cycle/main.pony create mode 100644 test/full-program-tests/embed-gc-actor-nested-embed-cycle/main.pony create mode 100644 test/full-program-tests/embed-gc-actor-outlives-field-holder/main.pony create mode 100644 test/full-program-tests/embed-gc-actor-outlives-field-holder/program-args.txt create mode 100644 test/full-program-tests/embed-gc-actor-struct-start-own/main.pony create mode 100644 test/full-program-tests/embed-gc-actor-struct-start-send/main.pony create mode 100644 test/full-program-tests/embed-gc-actor-too-large-for-an-arena/main.pony create mode 100644 test/full-program-tests/embed-gc-actor-too-large-for-an-arena/program-args.txt create mode 100644 test/full-program-tests/embed-gc-actor-val-field-send/main.pony create mode 100644 test/full-program-tests/embed-gc-class-field-only/main.pony create mode 100644 test/full-program-tests/embed-gc-embedded-field-cycle/main.pony create mode 100644 test/full-program-tests/embed-gc-large-struct-field-first-mark/main.pony create mode 100644 test/full-program-tests/embed-gc-nested-struct-start-local/main.pony create mode 100644 test/full-program-tests/embed-gc-nested-struct-start-message/main.pony create mode 100644 test/full-program-tests/embed-gc-pointer-at-struct-start-send/main.pony create mode 100644 test/full-program-tests/embed-gc-pointer-at-struct-start/main.pony create mode 100644 test/full-program-tests/embed-gc-pool-memory-not-an-actor/main.pony create mode 100644 test/full-program-tests/embed-gc-remote-struct-and-field/main.pony create mode 100644 test/full-program-tests/embed-gc-routed-tag-in-boxed-tuple/main.pony create mode 100644 test/full-program-tests/embed-gc-struct-field-first-mark/main.pony create mode 100644 test/full-program-tests/embed-gc-struct-field-first-message/main.pony create mode 100644 test/full-program-tests/embed-gc-struct-field-first-through-interface/main.pony create mode 100644 test/full-program-tests/embed-gc-struct-field-first-through-nested-union/main.pony create mode 100644 test/full-program-tests/embed-gc-struct-field-separate-messages/main.pony create mode 100644 test/full-program-tests/embed-gc-struct-fields-without-the-struct/main.pony create mode 100644 test/full-program-tests/embed-gc-struct-first-field-only/main.pony create mode 100644 test/full-program-tests/embed-gc-visit-set-keyed-by-type/main.pony create mode 100644 test/full-program-tests/gc-pointer-at-struct-start-send/main.pony create mode 100644 test/full-program-tests/gc-pointer-at-struct-start/main.pony create mode 100644 test/libponyc/codegen_embed.cc create mode 100644 test/libponyc/codegen_sections.cc create mode 100644 test/libponyrt/gc/embed.cc create mode 100644 test/libponyrt/gc/sections.cc create mode 100644 test/libponyrt/gc/test_sections.h create mode 100644 test/libponyrt/gc/test_type.h create mode 100644 test/libponyrt/noscript/noscript.c diff --git a/.gitattributes b/.gitattributes index 5a7f845da7b..3bade7dd388 100644 --- a/.gitattributes +++ b/.gitattributes @@ -8,6 +8,7 @@ *.yml pony *.sh pony *.bash pony +*.ld pony *.bat win *.diff pony diff --git a/.release-notes/next-release.md b/.release-notes/next-release.md index 48bccee285e..1bce2f9845e 100644 --- a/.release-notes/next-release.md +++ b/.release-notes/next-release.md @@ -2228,3 +2228,53 @@ A match with one case that is a sequence ending in `true` and another that is a We've updated the LLVM version used to build Pony from 23.1.3 to 23.1.7. +## Fix GC freeing the other fields of a struct whose first field is embedded + +A Pony `struct` has no object header. When the first field of a struct is embedded, the struct and that field have the same address. + +A program can hold a reference to that embedded field apart from the struct. Before this fix, the runtime could then trace that address as the type of the field and never trace it as the struct. The runtime did not trace the other fields of the struct. The runtime freed the memory of those fields and reused it while the struct still pointed at them. This happened during garbage collection of an actor's heap and during the trace of a message that an actor sends. + +For example, struct `S` embeds a `C` in its first field `c` and has a second field `d`. An actor holds `_s.c` in its field `_c`, and the actor declares `_c` before its field `_s`. Before this fix, reads of `_s.d.n` could stop returning the value that `_s.d.n` was created with. Whether the reads returned a wrong value depended on when garbage collection ran, so the wrong values did not occur in every run of the program. + +Now the other fields of the struct stay alive while the struct is reachable. + +## Fix tracing that never finishes when a reference cycle runs through embedded objects + +Embedded objects can form a reference cycle. Before this fix, the runtime's trace went around that cycle again and again and never finished. This happened during garbage collection and during the trace of a message that an actor sends. The simplest case is an embedded object that references itself. + +Three forms of the cycle caused the hang: + +- An embedded field inside a class object on the Pony heap, during garbage collection. This includes a cycle through two such objects. +- An embedded field of an actor, during garbage collection. +- An embedded `val` field of an actor, when the actor sends that field. + +For example, class `A` embeds a `C` in its field `c`, and `C` has a field `self_ref`. The program sets `a.c.self_ref` to `a.c` and keeps only `a.c`. Before this fix, that program hung. Now the trace finishes. + +## Fix an actor being collected while another actor holds its embedded field + +An actor can send an embedded `val` field to another actor and then have no more work to do. Before this fix, the runtime could collect the sending actor while the other actor still held the field. The runtime could then reuse the memory of the sending actor for actors that the program created later. + +Now the sending actor stays alive while another actor holds its embedded field. + +## Fix GC freeing a struct's fields when a Pointer points at its start + +To get this bug, your program must make a `Pointer` through FFI. If your program uses no FFI, this bug does not affect it. + +A class can hold a `Pointer` to the start of a struct and also hold the struct itself, with the `Pointer` field first. Before this fix, the runtime could free the fields of the struct while they were still reachable. This happened in two cases: + +- During garbage collection, the runtime freed a field of the struct while the class still held the struct. +- When an actor sent such a class to another actor, the runtime did not count the field of the struct for the receiving actor. The sending actor then freed the field while the receiving actor still held it. + +Now the fields of the struct stay alive. + +## Fix the address of an embedded struct with no size + +Before this fix, an embedded struct with no size got the address where it would sit in the object that holds it. For a field at the end of that object, this address is one past the end of the object. That address can be the address of a different object. + +Now an embedded struct with no size has the address of the object that holds it, wherever the field is declared. Its address is always inside that object. As a result, `digestof` of the field gives the same value as `digestof` of the object that holds it, and `is` between the two gives `true`. Two embedded structs with no size in the same object are also `is` each other. + +## Speed up GC for string and array literals + +The compiler creates string literals, constant array literals, and primitive instances as constants. A program can never free these objects. The garbage collector now skips these objects and no longer traces them. + +In one of our benchmarks, an actor holds many references to string literals and collects its garbage at the end of every behavior. With release builds and one scheduler thread, that actor now does about 4.7 times as many collections per second: 904.0 instead of 193.5. A second version of the benchmark went from 197.2 to 840.4 collections per second, about 4.3 times as many. Our other benchmarks changed by about 1–2%. diff --git a/BUILD.md b/BUILD.md index 12352a0b78a..fd5226795fc 100644 --- a/BUILD.md +++ b/BUILD.md @@ -483,6 +483,10 @@ cmake --preset release -DPONY_USES=reach_instrument cmake --build --preset release ``` +## Linker for the runtime tests + +On ELF platforms, `libponyrt.tests` links with the linker script `src/libponyrt/gc/pony_sections.ld`, the same script ponyc writes when it links a program. GNU ld and lld accept it. gold doesn't support its `INSERT` command and mold doesn't support its `SECTIONS` command. With either of them as the host linker, the build links the runtime tests without the script, and the tests that check the sections it marks skip. + ## Compiler Development To ease development and support LSP tools like [clangd](https://clangd.llvm.org), create a `compile_commands.json` file with the following steps: diff --git a/CHANGELOG.md b/CHANGELOG.md index 5ee8af1b3eb..6990acb7ee4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,12 @@ All notable changes to the Pony compiler and standard library will be documented ### Fixed +- Fix GC freeing the other fields of a struct whose first field is embedded ([PR #7085](https://github.com/ponylang/ponyc/pull/7085)) +- Fix tracing that never finishes when a reference cycle runs through embedded objects ([PR #7085](https://github.com/ponylang/ponyc/pull/7085)) +- Fix an actor being collected while another actor holds its embedded field ([PR #7085](https://github.com/ponylang/ponyc/pull/7085)) +- Fix GC freeing a struct's fields when a Pointer points at its start ([PR #7085](https://github.com/ponylang/ponyc/pull/7085)) +- Fix the address of an embedded struct with no size ([PR #7085](https://github.com/ponylang/ponyc/pull/7085)) +- Speed up GC for string and array literals ([PR #7085](https://github.com/ponylang/ponyc/pull/7085)) - Fix ponyc merging runtime bitcode built for another target ([PR #7021](https://github.com/ponylang/ponyc/pull/7021)) - Fix macOS programs built for a darwin target triple ([PR #7021](https://github.com/ponylang/ponyc/pull/7021)) - Fix object literals and lambdas that use consumed variables or variables with no value ([PR #7029](https://github.com/ponylang/ponyc/pull/7029)) diff --git a/CMakeLists.txt b/CMakeLists.txt index 6cb01d5299c..68a9b7f065b 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -683,6 +683,21 @@ add_custom_target(pony_version ALL COMMENT "Refreshing pony_version.h" ) +# The linker script ponyc writes for each ELF link, embedded as a C string. +set(PONY_SECTIONS_LINKER_SCRIPT "${CMAKE_SOURCE_DIR}/src/libponyrt/gc/pony_sections.ld") +set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS + "${PONY_SECTIONS_LINKER_SCRIPT}") +file(READ "${PONY_SECTIONS_LINKER_SCRIPT}" _pony_sections_script) +string(REPLACE "\\" "\\\\" _pony_sections_script "${_pony_sections_script}") +string(REPLACE "\"" "\\\"" _pony_sections_script "${_pony_sections_script}") +string(REPLACE "\n" "\\n\"\n \"" _pony_sections_script "${_pony_sections_script}") +file(WRITE "${CMAKE_BINARY_DIR}/pony_generated/pony_sections_ld.h.tmp" +"// Generated by CMake from src/libponyrt/gc/pony_sections.ld. Do not edit.\n" +"#pragma once\n" +"static const char PONY_SECTIONS_LINKER_SCRIPT[] =\n \"${_pony_sections_script}\";\n") +configure_file("${CMAKE_BINARY_DIR}/pony_generated/pony_sections_ld.h.tmp" + "${CMAKE_BINARY_DIR}/pony_generated/pony_sections_ld.h" COPYONLY) + # Required definitions. We use these generators so that the defines are correct for both *nix (where the config applies at configuration time) and Windows (where the config applies at build time). add_compile_definitions( BUILD_COMPILER="${CMAKE_C_COMPILER_VERSION}" @@ -954,6 +969,12 @@ else() set_tests_properties(check-version libponyrt.tests libponyc.tests PROPERTIES LABELS ci-core) + if(TARGET libponyrt.noscript) + add_test(NAME libponyrt.noscript + COMMAND $) + set_tests_properties(libponyrt.noscript PROPERTIES LABELS ci-core) + endif() + if(PONY_RUNTIME_BITCODE) set(_check_bitcode_macos_args "") if(APPLE) diff --git a/cmake/RunLinkHandoff.cmake b/cmake/RunLinkHandoff.cmake index d866e946301..00fcb62bc0e 100644 --- a/cmake/RunLinkHandoff.cmake +++ b/cmake/RunLinkHandoff.cmake @@ -9,7 +9,8 @@ # info into place. At -V3, the compiler prints its process ID and its parent's # and, for each link, whether it runs the link or hands it off; ponylink prints # its process ID and its parent's. A handed-off link's ponylink has the -# compiler's parent (the driver) as its parent. +# compiler's parent (the driver) as its parent. On ELF, the test also checks +# how a link handles ponyc's linker script. # # Args (passed with -D): PONYC (the driver), PONYC_COMPILER (the compiler # binary), PONYLINK (the ponylink binary), LAUNCHER @@ -95,7 +96,7 @@ endfunction() # finished, successful or not. function(check_no_temporaries _name _dir _text) file(GLOB _left - "${_dir}/*.bc" "${_dir}/*.lldargs" + "${_dir}/*.bc" "${_dir}/*.lldargs" "${_dir}/*.ponyc.ld" "${_dir}/*.tmp" "${_dir}/*.lto_objects") if(_left) fail("${_name}: left behind ${_left}" "${_text}") @@ -170,11 +171,20 @@ function(check_compiler_link _name _text) endif() endfunction() -# One package. +# One package. A linker script of the user's own, named after the program, +# is left as it was. +file(WRITE "${_fixture}/out-single/a.ld" "/* the user's */\n") run_ponyc(single "${_fixture}" -V3 -o out-single a) if(NOT single_rc EQUAL 0) fail("single: ponyc exited ${single_rc}" "${single_text}") endif() +if(NOT EXISTS "${_fixture}/out-single/a.ld") + fail("single: the link removed out-single/a.ld" "${single_text}") +endif() +file(READ "${_fixture}/out-single/a.ld" _user_script) +if(NOT _user_script STREQUAL "/* the user's */\n") + fail("single: the link changed out-single/a.ld" "${single_text}") +endif() check_last_link("single" "${single_text}") check_runs("single" "${_fixture}/out-single/a" "a" "${single_text}") check_no_temporaries("single" "${_fixture}/out-single" "${single_text}") @@ -489,6 +499,70 @@ if(_left OR EXISTS "${_fixture}/out-argsfail/b") fail("argsfail: left ${_left} or linked anyway" "${argsfail_text}") endif() +# The linker script can't be written (a non-empty directory sits at its path, +# on the ELF platforms that use one): ponyc reports it and fails, no program is +# left, and the link's temporary files are removed. +if(NOT CMAKE_HOST_SYSTEM_NAME STREQUAL "Darwin") + file(MAKE_DIRECTORY "${_fixture}/out-scriptfail/b.ponyc.ld/blocker") + run_ponyc(scriptfail "${_fixture}" -o out-scriptfail b) + if(NOT scriptfail_rc EQUAL 255) + fail("scriptfail: ponyc exited ${scriptfail_rc}, not 255" + "${scriptfail_text}") + endif() + if(NOT scriptfail_text MATCHES + "failed to write linker script [^\n]*b\\.ponyc\\.ld: [^\n]+") + fail("scriptfail: no message with the script's path and the reason" + "${scriptfail_text}") + endif() + file(GLOB _left "${_fixture}/out-scriptfail/*.bc" + "${_fixture}/out-scriptfail/*.lldargs" + "${_fixture}/out-scriptfail/*.tmp") + if(_left OR EXISTS "${_fixture}/out-scriptfail/b") + fail("scriptfail: left ${_left} or linked anyway" "${scriptfail_text}") + endif() + + # A program linked without the linker script, as when someone links the + # compiler's objects by hand, links and runs with the script's section + # symbols undefined. The program has a Holder (an actor with an embedded + # field), so the runtime must find an actor from its field without the + # descriptor section; the case checks only that the program runs. + file(MAKE_DIRECTORY "${_fixture}/noscript/src") + file(WRITE "${_fixture}/noscript/src/main.pony" + "class C\n var n: U64 = 7\n" + "actor Keeper\n var _c: (C tag | None) = None\n" + " be take(c: C tag) => _c = c\n" + "actor Holder\n embed c: C = C\n" + " new create(k: Keeper) => k.take(c)\n" + "actor Main\n new create(env: Env) =>\n" + " let k = Keeper\n var i: USize = 0\n" + " while i < 100 do Holder(k); i = i + 1 end\n") + run_launched(noscript_build "${_fixture}/noscript" --handoff-pipe + -- "${PONYC_COMPILER}" -o out src) + if(NOT noscript_build_text MATCHES "(^|\n)exited 0\n") + fail("noscript: the compile failed" "${noscript_build_text}") + endif() + file(READ "${_fixture}/noscript/out/src.lldargs" _args) + string(REGEX REPLACE "(^|\n)-T\n[^\n]*\n" "\\1" _text "${_args}") + if(_text STREQUAL _args) + fail("noscript: the link has no linker script to leave out" + "${noscript_build_text}") + endif() + file(WRITE "${_fixture}/noscript/noscript.lldargs" "${_text}") + execute_process( + COMMAND "${PONYLINK}" --ponyc-job + --args "${_fixture}/noscript/noscript.lldargs" + WORKING_DIRECTORY "${_fixture}/noscript" + RESULT_VARIABLE _rc OUTPUT_VARIABLE _out ERROR_VARIABLE _out) + if(NOT _rc EQUAL 0) + fail("noscript: ponylink exited ${_rc}" "${_out}") + endif() + execute_process(COMMAND "${_fixture}/noscript/out/src" + RESULT_VARIABLE _rc OUTPUT_VARIABLE _out ERROR_VARIABLE _out) + if(NOT _rc EQUAL 0) + fail("noscript: the program exited ${_rc}" "${_out}") + endif() +endif() + # An option ponylink doesn't know: a usage error, and ponylink removes nothing. set(_sentinel "${_fixture}/sentinel") file(WRITE "${_sentinel}" "keep\n") diff --git a/cmake/RunNoAllocLink.cmake b/cmake/RunNoAllocLink.cmake index 325c0db63e6..ce4c7183fdb 100644 --- a/cmake/RunNoAllocLink.cmake +++ b/cmake/RunNoAllocLink.cmake @@ -65,6 +65,7 @@ set(_rejected_methods "__make_|a heap allocation" "__one_|a heap allocation" "__escape_|a heap allocation" + "__shared_|a heap allocation" "Holder_[a-z]+_create_|a heap allocation" "__ffi_|an FFI call") diff --git a/cmake/RunOutputFileLinks.cmake b/cmake/RunOutputFileLinks.cmake index fe69bff7f48..f140cbf377d 100644 --- a/cmake/RunOutputFileLinks.cmake +++ b/cmake/RunOutputFileLinks.cmake @@ -190,6 +190,23 @@ foreach(_kind IN LISTS _kinds) fail("${_case}" "${_names} was left behind") endif() + # The linker script, which ponyc writes for an ELF link and ponylink + # removes after the link. + if(NOT WIN32 AND NOT CMAKE_HOST_SYSTEM_NAME STREQUAL "Darwin") + set(_case "script-${_kind}") + set(_out "${_fixture}/out-${_case}") + set(_names prog.ponyc.ld) + plant("${_out}" ${_kind} ${_names}) + run_ponyc(prog -o "${_out}" -b prog .) + if(NOT _rc EQUAL 0) + fail("${_case}" "ponyc exited ${_rc}\n${_text}") + endif() + check_victims("${_case}" "${_out}" ${_names}) + if(EXISTS "${_out}/${_names}") + fail("${_case}" "${_names} was left behind") + endif() + endif() + # The mutation info, and the coverage file that the program writes when # it exits. Except on Windows, ponyc writes the mutation info to a # temporary file that ponylink renames after the link. The program names diff --git a/src/common/platform.h b/src/common/platform.h index 1776d0d87dc..3c137f11674 100644 --- a/src/common/platform.h +++ b/src/common/platform.h @@ -21,6 +21,15 @@ # define PONY_EXTERN_C_END #endif +/** Inline a function into every caller, whatever the optimiser would choose. + * + */ +#if defined(_MSC_VER) +# define PONY_FORCEINLINE __forceinline +#else +# define PONY_FORCEINLINE inline __attribute__((always_inline)) +#endif + /** Determines the operating system. * */ diff --git a/src/common/pony_section_names.h b/src/common/pony_section_names.h new file mode 100644 index 00000000000..4082de2ce64 --- /dev/null +++ b/src/common/pony_section_names.h @@ -0,0 +1,27 @@ +#ifndef PONY_SECTION_NAMES_H +#define PONY_SECTION_NAMES_H + +/* The sections the compiler puts its type descriptors and its other constants + * in, and whose bounds the runtime reads. The ELF names are also in the linker + * script libponyrt/gc/pony_sections.ld, which can't include this header. + */ + +#define PONY_ELF_DESC_SECTION ".data.rel.ro.pony-desc" +#define PONY_ELF_CONST_SECTION ".data.rel.ro.pony-const" + +#define PONY_MACHO_SEGMENT "__DATA_CONST" +#define PONY_MACHO_DESC_SECTION "__pony_desc" +#define PONY_MACHO_CONST_SECTION "__pony_const" + +/* The COFF linker merges the .ponyc$ sections into one, ordered by the text + * after the $. The descriptors are between the runtime's markers in the + * DESC_START and CONST_START sections, and the other constants between the + * markers in the CONST_START and CONST_END sections. + */ +#define PONY_COFF_DESC_START_SECTION ".ponyc$a" +#define PONY_COFF_DESC_SECTION ".ponyc$d" +#define PONY_COFF_CONST_START_SECTION ".ponyc$e" +#define PONY_COFF_CONST_SECTION ".ponyc$m" +#define PONY_COFF_CONST_END_SECTION ".ponyc$z" + +#endif diff --git a/src/libponyc/codegen/codegen.c b/src/libponyc/codegen/codegen.c index 53ed06aa8be..92df7ea2689 100644 --- a/src/libponyc/codegen/codegen.c +++ b/src/libponyc/codegen/codegen.c @@ -251,6 +251,30 @@ static void set_runtime_attrs(compile_t* c) LLVMAddAttributeAtIndex(fn, LLVMAttributeReturnIndex, align_heap_attr); } + fn = LLVMGetNamedFunction(c->module, "pony_alloc_small_shared_start"); + if(fn != NULL) + { + LLVMAddAttributeAtIndex(fn, LLVMAttributeFunctionIndex, nounwind_attr); + LLVMAddAttributeAtIndex(fn, LLVMAttributeFunctionIndex, + inacc_or_arg_mem_attr); + LLVMAddAttributeAtIndex(fn, LLVMAttributeReturnIndex, noalias_attr); + LLVMAddAttributeAtIndex(fn, LLVMAttributeReturnIndex, + deref_alloc_small_attr); + LLVMAddAttributeAtIndex(fn, LLVMAttributeReturnIndex, align_heap_attr); + } + + fn = LLVMGetNamedFunction(c->module, "pony_alloc_large_shared_start"); + if(fn != NULL) + { + LLVMAddAttributeAtIndex(fn, LLVMAttributeFunctionIndex, nounwind_attr); + LLVMAddAttributeAtIndex(fn, LLVMAttributeFunctionIndex, + inacc_or_arg_mem_attr); + LLVMAddAttributeAtIndex(fn, LLVMAttributeReturnIndex, noalias_attr); + LLVMAddAttributeAtIndex(fn, LLVMAttributeReturnIndex, + deref_alloc_large_attr); + LLVMAddAttributeAtIndex(fn, LLVMAttributeReturnIndex, align_heap_attr); + } + fn = LLVMGetNamedFunction(c->module, "pony_realloc"); if(fn != NULL) { @@ -324,6 +348,15 @@ static void set_runtime_attrs(compile_t* c) LLVMAddAttributeAtIndex(fn, 2, readonly_attr); } + fn = LLVMGetNamedFunction(c->module, "pony_traceknown_routed"); + if(fn != NULL) + { + LLVMAddAttributeAtIndex(fn, LLVMAttributeFunctionIndex, nounwind_attr); + LLVMAddAttributeAtIndex(fn, LLVMAttributeFunctionIndex, + inacc_or_arg_mem_attr); + LLVMAddAttributeAtIndex(fn, 2, readonly_attr); + } + fn = LLVMGetNamedFunction(c->module, "pony_traceunknown"); if(fn != NULL) { @@ -333,6 +366,15 @@ static void set_runtime_attrs(compile_t* c) LLVMAddAttributeAtIndex(fn, 2, readonly_attr); } + fn = LLVMGetNamedFunction(c->module, "pony_traceunknown_routed"); + if(fn != NULL) + { + LLVMAddAttributeAtIndex(fn, LLVMAttributeFunctionIndex, nounwind_attr); + LLVMAddAttributeAtIndex(fn, LLVMAttributeFunctionIndex, + inacc_or_arg_mem_attr); + LLVMAddAttributeAtIndex(fn, 2, readonly_attr); + } + fn = LLVMGetNamedFunction(c->module, "pony_gc_send"); if(fn != NULL) { @@ -474,6 +516,18 @@ static void init_runtime_decls(compile_t* c) type = LLVMFunctionType(c->ptr, params, 2, false); value = LLVMAddFunction(c->module, "pony_alloc_large", type); + // i8* pony_alloc_small_shared_start(i8*, i32) + params[0] = c->ptr; + params[1] = c->i32; + type = LLVMFunctionType(c->ptr, params, 2, false); + value = LLVMAddFunction(c->module, "pony_alloc_small_shared_start", type); + + // i8* pony_alloc_large_shared_start(i8*, intptr) + params[0] = c->ptr; + params[1] = c->intptr; + type = LLVMFunctionType(c->ptr, params, 2, false); + value = LLVMAddFunction(c->module, "pony_alloc_large_shared_start", type); + // i8* pony_realloc(i8*, i8*, intptr, intptr) params[0] = c->ptr; params[1] = c->ptr; @@ -520,6 +574,9 @@ static void init_runtime_decls(compile_t* c) type = LLVMFunctionType(c->void_type, params, 4, false); value = LLVMAddFunction(c->module, "pony_traceknown", type); + // void pony_traceknown_routed(i8*, __object*, __Desc*, i32) + value = LLVMAddFunction(c->module, "pony_traceknown_routed", type); + // void pony_traceunknown(i8*, __object*, i32) params[0] = c->ptr; params[1] = c->ptr; @@ -527,6 +584,9 @@ static void init_runtime_decls(compile_t* c) type = LLVMFunctionType(c->void_type, params, 3, false); value = LLVMAddFunction(c->module, "pony_traceunknown", type); + // void pony_traceunknown_routed(i8*, __object*, i32) + value = LLVMAddFunction(c->module, "pony_traceunknown_routed", type); + // void pony_gc_send(i8*, __actor*) params[0] = c->ptr; params[1] = c->ptr; @@ -1600,6 +1660,38 @@ static void stamp_module_target_attrs(compile_t* c, LLVMModuleRef module) } } +void codegen_place_in_constant_section(compile_t* c, LLVMValueRef global) +{ + const char* section = target_constant_section(c->opt->triple); + + if(section == NULL) + return; + + LLVMSetSection(global, section); + + LLVMLinkage linkage = LLVMGetLinkage(global); + + if((linkage == LLVMPrivateLinkage) || (linkage == LLVMInternalLinkage)) + { + char name[64]; + snprintf(name, sizeof(name), "ponyc.const.%zu", c->constant_object_count++); + LLVMSetValueName2(global, name, strlen(name)); + LLVMSetLinkage(global, LLVMExternalLinkage); + LLVMSetVisibility(global, LLVMHiddenVisibility); + } +} + +void codegen_place_in_descriptor_section(compile_t* c, LLVMValueRef global) +{ + const char* section = target_descriptor_section(c->opt->triple); + + if(section == NULL) + return; + + pony_assert(LLVMGetLinkage(global) == LLVMExternalLinkage); + LLVMSetSection(global, section); +} + void codegen_stamp_target_attrs(compile_t* c) { if(c->per_module_count > 0) diff --git a/src/libponyc/codegen/codegen.h b/src/libponyc/codegen/codegen.h index b98c20cfc69..f4d8ec7b4b0 100644 --- a/src/libponyc/codegen/codegen.h +++ b/src/libponyc/codegen/codegen.h @@ -256,6 +256,11 @@ typedef struct compile_t size_t per_module_count; size_t current_module_index; + // The number of constant objects codegen_place_in_constant_section has + // renamed, used to give each a name unique across every module of the + // program. + size_t constant_object_count; + bool runtime_bitcode_merged; mutate_state_t mutate; @@ -299,6 +304,16 @@ void codegen_dispose_modules(compile_t* c); void codegen_stamp_target_attrs(compile_t* c); +// Places a global the compiler emits as a constant object in the target's +// constant section (see target_constant_section). A private or internal global +// becomes a hidden global with a unique name: ThinLTO won't import a function +// that refers to a local global with a section. +void codegen_place_in_constant_section(compile_t* c, LLVMValueRef global); + +// Places a type descriptor, which has external linkage, in the target's +// descriptor section (see target_descriptor_section). +void codegen_place_in_descriptor_section(compile_t* c, LLVMValueRef global); + void codegen_switch_module(compile_t* c, size_t index); size_t codegen_create_per_module_state(compile_t* c, const char* mod_sym, diff --git a/src/libponyc/codegen/gencall.c b/src/libponyc/codegen/gencall.c index 7c6b9646bd6..c6279abe175 100644 --- a/src/libponyc/codegen/gencall.c +++ b/src/libponyc/codegen/gencall.c @@ -8,6 +8,7 @@ #include "genfun.h" #include "genname.h" #include "gentagged.h" +#include "gentype.h" #include "genopt.h" #include "gentrace.h" #include "../pkg/platformfuns.h" @@ -2281,17 +2282,25 @@ LLVMValueRef gencall_allocstruct(compile_t* c, reach_type_t* t) if(size == 0) size = 1; + // The shared-start allocators have no finaliser variant. + bool shared_start = gentype_first_embed(c, t) != NULL; + pony_assert(!shared_start || (c_t->final_fn == NULL)); + if(size <= HEAP_MAX) { uint32_t index = ponyint_heap_index(size); args[1] = LLVMConstInt(c->i32, index, false); - if(c_t->final_fn == NULL) + if(shared_start) + result = gencall_runtime(c, "pony_alloc_small_shared_start", args, 2, ""); + else if(c_t->final_fn == NULL) result = gencall_runtime(c, "pony_alloc_small", args, 2, ""); else result = gencall_runtime(c, "pony_alloc_small_final", args, 2, ""); } else { args[1] = LLVMConstInt(c->intptr, size, false); - if(c_t->final_fn == NULL) + if(shared_start) + result = gencall_runtime(c, "pony_alloc_large_shared_start", args, 2, ""); + else if(c_t->final_fn == NULL) result = gencall_runtime(c, "pony_alloc_large", args, 2, ""); else result = gencall_runtime(c, "pony_alloc_large_final", args, 2, ""); diff --git a/src/libponyc/codegen/gendesc.c b/src/libponyc/codegen/gendesc.c index 059bad336c4..58e734f6000 100644 --- a/src/libponyc/codegen/gendesc.c +++ b/src/libponyc/codegen/gendesc.c @@ -13,24 +13,6 @@ #include "ponyassert.h" #include -#define DESC_ID 0 -#define DESC_SIZE 1 -#define DESC_FIELD_COUNT 2 -#define DESC_FIELD_OFFSET 3 -#define DESC_INSTANCE 4 -#define DESC_NAME 5 -#define DESC_GET_BEHAVIOR_NAME 6 -#define DESC_TRACE 7 -#define DESC_DISPATCH 8 -#define DESC_FINALISE 9 -#define DESC_EVENT_NOTIFY 10 -#define DESC_MIGHT_REFERENCE_ACTOR 11 -#define DESC_TRAITS 12 -#define DESC_FIELDS 13 -#define DESC_VTABLE 14 - -#define DESC_LENGTH 15 - static LLVMValueRef make_unbox_function(compile_t* c, reach_type_t* t, reach_method_t* m) { @@ -232,16 +214,19 @@ static LLVMValueRef make_field_offset(compile_t* c, reach_type_t* t) return LLVMConstInt(c->i32, 0, false); } - int index = 0; + return LLVMConstInt(c->i32, + LLVMOffsetOfElement(c->target_data, c_t->structure, + gentype_field_index(t, 0)), false); +} - if(t->underlying != TK_STRUCT) - index++; +static LLVMValueRef make_first_embed(compile_t* c, reach_type_t* t) +{ + reach_type_t* f = gentype_first_embed(c, t); - if(t->underlying == TK_ACTOR) - index++; + if(f == NULL) + return LLVMConstNull(c->ptr); - return LLVMConstInt(c->i32, - LLVMOffsetOfElement(c->target_data, c_t->structure, index), false); + return codegen_resolve_global(c, ((compile_type_t*)f->c_type)->desc); } static LLVMValueRef make_might_reference_actor(compile_t* c, reach_type_t* t) @@ -372,6 +357,7 @@ void gendesc_basetype(compile_t* c, LLVMTypeRef desc_type) params[DESC_FINALISE] = c->ptr; params[DESC_EVENT_NOTIFY] = c->i32; params[DESC_MIGHT_REFERENCE_ACTOR] = c->i1; + params[DESC_EMBED_FLAGS] = c->i8; params[DESC_TRAITS] = c->ptr; params[DESC_FIELDS] = c->ptr; params[DESC_VTABLE] = LLVMArrayType(c->ptr, 0); @@ -416,6 +402,7 @@ void gendesc_type(compile_t* c, reach_type_t* t) params[DESC_FINALISE] = c->ptr; params[DESC_EVENT_NOTIFY] = c->i32; params[DESC_MIGHT_REFERENCE_ACTOR] = c->i1; + params[DESC_EMBED_FLAGS] = c->i8; params[DESC_TRAITS] = c->ptr; params[DESC_FIELDS] = c->ptr; params[DESC_VTABLE] = LLVMArrayType(c->ptr, vtable_size); @@ -425,6 +412,7 @@ void gendesc_type(compile_t* c, reach_type_t* t) c_t->desc = LLVMAddGlobal(c->module, c_t->desc_type, desc_name); LLVMSetGlobalConstant(c_t->desc, true); LLVMSetLinkage(c_t->desc, LLVMExternalLinkage); + codegen_place_in_descriptor_section(c, c_t->desc); } void gendesc_init(compile_t* c, reach_type_t* t) @@ -442,7 +430,10 @@ void gendesc_init(compile_t* c, reach_type_t* t) args[DESC_SIZE] = LLVMConstInt(c->i32, c_t->abi_size, false); args[DESC_FIELD_COUNT] = make_field_count(c, t); args[DESC_FIELD_OFFSET] = make_field_offset(c, t); - args[DESC_INSTANCE] = make_desc_ptr(c, c_t->instance); + if(t->underlying == TK_STRUCT) + args[DESC_INSTANCE] = make_first_embed(c, t); + else + args[DESC_INSTANCE] = make_desc_ptr(c, c_t->instance); args[DESC_NAME] = make_name(c, t); args[DESC_GET_BEHAVIOR_NAME] = make_desc_ptr(c, c_t->get_behavior_name_fn); args[DESC_TRACE] = make_desc_ptr(c, c_t->trace_fn); @@ -450,6 +441,7 @@ void gendesc_init(compile_t* c, reach_type_t* t) args[DESC_FINALISE] = make_desc_ptr(c, c_t->final_fn); args[DESC_EVENT_NOTIFY] = LLVMConstInt(c->i32, event_notify_index, false); args[DESC_MIGHT_REFERENCE_ACTOR] = make_might_reference_actor(c, t); + args[DESC_EMBED_FLAGS] = LLVMConstInt(c->i8, c_t->embed_flags, false); args[DESC_TRAITS] = make_trait_bitmap(c, t); args[DESC_FIELDS] = make_field_list(c, t); args[DESC_VTABLE] = make_vtable(c, t); diff --git a/src/libponyc/codegen/gendesc.h b/src/libponyc/codegen/gendesc.h index eb095a70640..82b3f9aa889 100644 --- a/src/libponyc/codegen/gendesc.h +++ b/src/libponyc/codegen/gendesc.h @@ -6,6 +6,27 @@ PONY_EXTERN_C_BEGIN +// The index of each field of a type descriptor, in the order of _pony_type_t in +// pony.h. +#define DESC_ID 0 +#define DESC_SIZE 1 +#define DESC_FIELD_COUNT 2 +#define DESC_FIELD_OFFSET 3 +#define DESC_INSTANCE 4 +#define DESC_NAME 5 +#define DESC_GET_BEHAVIOR_NAME 6 +#define DESC_TRACE 7 +#define DESC_DISPATCH 8 +#define DESC_FINALISE 9 +#define DESC_EVENT_NOTIFY 10 +#define DESC_MIGHT_REFERENCE_ACTOR 11 +#define DESC_EMBED_FLAGS 12 +#define DESC_TRAITS 13 +#define DESC_FIELDS 14 +#define DESC_VTABLE 15 + +#define DESC_LENGTH 16 + void gendesc_basetype(compile_t* c, LLVMTypeRef desc_type); void gendesc_type(compile_t* c, reach_type_t* t); diff --git a/src/libponyc/codegen/genexe.cc b/src/libponyc/codegen/genexe.cc index ca8388ebc16..76a216cc62d 100644 --- a/src/libponyc/codegen/genexe.cc +++ b/src/libponyc/codegen/genexe.cc @@ -4,6 +4,7 @@ #include "genexport.h" #include "gencall.h" #include "genfun.h" +#include "gentrace.h" #include "genname.h" #include "genobj.h" #include "genopt.h" @@ -17,6 +18,7 @@ #include "../ast/stringtab.h" #include "../pkg/package.h" #include "../pkg/program.h" +#include "pony_sections_ld.h" #include "../plugin/plugin.h" #include "../type/assemble.h" #include "../type/lookup.h" @@ -29,6 +31,7 @@ #include "../../common/run_command.h" #include "../ponyc.h" #include "ponyassert.h" +#include #include #if defined(__GLIBC__) # include @@ -212,11 +215,7 @@ LLVMValueRef gen_main(compile_t* c, reach_type_t* t_main, reach_type_t* t_env) args[1] = LLVMConstNull(c->ptr); gencall_runtime(c, "pony_gc_send", args, 2, ""); - args[0] = ctx; - args[1] = env; - args[2] = codegen_resolve_global(c, ((compile_type_t*)t_env->c_type)->desc); - args[3] = LLVMConstInt(c->i32, PONY_TRACE_IMMUTABLE, false); - gencall_runtime(c, "pony_traceknown", args, 4, ""); + gentrace_known(c, ctx, env, t_env, PONY_TRACE_IMMUTABLE); args[0] = ctx; gencall_runtime(c, "pony_send_done", args, 1, ""); @@ -306,6 +305,9 @@ struct link_inputs_t // otherwise. const char* mutate_tmp = NULL; const char* mutate_final = NULL; + // A linker script the compiler wrote for this link, removed once the link + // finishes. NULL if there is none. + const char* linker_script = NULL; }; // A link ponylink will run with `--ponyc-job`, either now as the compiler's @@ -1102,17 +1104,15 @@ static const char* resolve_sysroot(compile_t* c, const char* sys_triple, return find_cross_toolchain_sysroot(c->opt, errors); } -// Write one entry per line to a new file at path. Returns 0, an errno value -// when the open or the close failed, or -1 when only a write failed. -static int write_lines(const std::string& path, - const std::vector& lines) +// Write text to a new file at path. Returns 0, an errno value when the open or +// the close failed, or -1 when only a write failed. +static int write_text(const std::string& path, const char* text) { FILE* f = ponyint_create_file(path.c_str(), 0600, PONY_CREATE_TEXT); if(f == NULL) return (errno != 0) ? errno : -1; - for(const std::string& line : lines) - fprintf(f, "%s\n", line.c_str()); + fputs(text, f); bool write_failed = (ferror(f) != 0); @@ -1122,6 +1122,22 @@ static int write_lines(const std::string& path, return write_failed ? -1 : 0; } +// Write one entry per line to a new file at path. Returns what write_text +// returns. +static int write_lines(const std::string& path, + const std::vector& lines) +{ + std::string text; + + for(const std::string& line : lines) + { + text += line; + text += '\n'; + } + + return write_text(path, text.c_str()); +} + // Run ponylink for the link and wait for it or, when opt->defer_link is set, // store the job in opt->pending_link for the caller to run. lto_objects is // the directory lld writes LTO objects to (macOS with debug info kept), or @@ -1189,6 +1205,9 @@ static bool run_link(compile_t* c, const char* file_exe, job->options.remove.push_back(args_path); + if(inputs->linker_script != NULL) + job->options.remove.push_back(inputs->linker_script); + if(lto_objects != NULL) job->options.remove_tree.push_back(lto_objects); @@ -2012,6 +2031,33 @@ static bool link_exe_lld_elf(compile_t* c, const link_inputs_t* inputs) args.push_back(stringtab(c->opt->strtab, buf)); } + // The linker script (src/libponyrt/gc/pony_sections.ld) places the compiler's + // type descriptors and its other constants where the runtime can find their + // bounds. + std::string script_path = std::string(file_exe) + ".ponyc.ld"; + + int err = write_text(script_path, PONY_SECTIONS_LINKER_SCRIPT); + + if(err != 0) + { + if(err > 0) + errorf(c->opt->check.errors, NULL, + "failed to write linker script %s: %s", script_path.c_str(), + strerror(err)); + else + errorf(c->opt->check.errors, NULL, "failed to write linker script %s", + script_path.c_str()); + + unlink(script_path.c_str()); + return false; + } + + link_inputs_t script_inputs = *inputs; + script_inputs.linker_script = script_path.c_str(); + + args.push_back("-T"); + args.push_back(script_path.c_str()); + args.push_back("-o"); args.push_back(file_exe); @@ -2027,7 +2073,13 @@ static bool link_exe_lld_elf(compile_t* c, const link_inputs_t* inputs) fprintf(stderr, "%s\n", cmd.c_str()); } - return run_link(c, file_exe, args, inputs, NULL, false); + // The link job removes the script, but run_link can fail before the job lists + // the script for removal, so remove it after any failure. + bool linked = run_link(c, file_exe, args, &script_inputs, NULL, false); + if(!linked) + unlink(script_path.c_str()); + + return linked; } static bool is_macos_sdk_root(const char* root) diff --git a/src/libponyc/codegen/genfun.c b/src/libponyc/codegen/genfun.c index 645c2789d0d..70eb4f91d08 100644 --- a/src/libponyc/codegen/genfun.c +++ b/src/libponyc/codegen/genfun.c @@ -7,6 +7,7 @@ #include "genexpr.h" #include "gengc.h" #include "genreference.h" +#include "gentype.h" #include "../pass/names.h" #include "../type/assemble.h" #include "../type/subtype.h" @@ -521,14 +522,6 @@ static void add_dispatch_case(compile_t* c, reach_type_t* t, static void call_embed_finalisers(compile_t* c, reach_type_t* t, ast_t* call_location, LLVMValueRef obj) { - compile_type_t* c_t = (compile_type_t*)t->c_type; - uint32_t base = 0; - if(t->underlying != TK_STRUCT) - base++; - - if(t->underlying == TK_ACTOR) - base++; - for(uint32_t i = 0; i < t->field_count; i++) { reach_field_t* field = &t->fields[i]; @@ -542,8 +535,7 @@ static void call_embed_finalisers(compile_t* c, reach_type_t* t, final_fn = codegen_resolve_function(c, final_fn); LLVMTypeRef final_fn_type = LLVMGlobalGetValueType(final_fn); - LLVMValueRef field_ref = LLVMBuildStructGEP2(c->builder, c_t->structure, - obj, base + i, ""); + LLVMValueRef field_ref = gentype_embed_ptr(c, t, obj, i); codegen_debugloc(c, call_location); LLVMBuildCall2(c->builder, final_fn_type, final_fn, &field_ref, 1, ""); codegen_debugloc(c, NULL); diff --git a/src/libponyc/codegen/genopt.cc b/src/libponyc/codegen/genopt.cc index e6a68bf22e6..3a1d6a049d8 100644 --- a/src/libponyc/codegen/genopt.cc +++ b/src/libponyc/codegen/genopt.cc @@ -1,4 +1,5 @@ #include "genopt.h" +#include "pony_section_names.h" #include @@ -778,6 +779,46 @@ bool target_is_windows(char* t) return triple.isOSWindows(); } +const char* target_constant_section(char* t) +{ + Triple triple = Triple(t); + + switch(triple.getObjectFormat()) + { + case Triple::ELF: + return PONY_ELF_CONST_SECTION; + + case Triple::MachO: + return PONY_MACHO_SEGMENT "," PONY_MACHO_CONST_SECTION; + + case Triple::COFF: + return PONY_COFF_CONST_SECTION; + + default: + return NULL; + } +} + +const char* target_descriptor_section(char* t) +{ + Triple triple = Triple(t); + + switch(triple.getObjectFormat()) + { + case Triple::ELF: + return PONY_ELF_DESC_SECTION; + + case Triple::MachO: + return PONY_MACHO_SEGMENT "," PONY_MACHO_DESC_SECTION; + + case Triple::COFF: + return PONY_COFF_DESC_SECTION; + + default: + return NULL; + } +} + bool target_is_posix(char* t) { Triple triple = Triple(t); diff --git a/src/libponyc/codegen/genopt.h b/src/libponyc/codegen/genopt.h index fa453aeb552..9cc4402f126 100644 --- a/src/libponyc/codegen/genopt.h +++ b/src/libponyc/codegen/genopt.h @@ -40,6 +40,16 @@ bool target_is_littleendian(char* triple); // LLVM labels a runtime built on an x86-64 or arm64 musl host as gnu. bool target_runtime_matches(const char* runtime, const char* target); +// The section the compiler puts its constant objects in for this target's +// object format, or NULL if it has none. The runtime doesn't trace objects in +// it. +const char* target_constant_section(char* triple); + +// The section the compiler puts its type descriptors in for this target's +// object format, or NULL if it has none. The runtime uses it to tell a +// descriptor from other constants. +const char* target_descriptor_section(char* triple); + // Target introspection shared by the executable linker (genexe) and the C // shim compiler (gencshim). They take pass_opt_t rather than the target_is_* // family's bare triple because system_triple also needs the interned-string diff --git a/src/libponyc/codegen/genreference.c b/src/libponyc/codegen/genreference.c index 236ea6c67e5..082fbaf18b8 100644 --- a/src/libponyc/codegen/genreference.c +++ b/src/libponyc/codegen/genreference.c @@ -70,17 +70,16 @@ static LLVMValueRef make_fieldptr(compile_t* c, LLVMValueRef l_value, ast_t* field = ast_get(def, name, NULL); uint32_t index = (uint32_t)ast_index(field); - if(ast_id(def) != TK_STRUCT) - index++; - - if(ast_id(def) == TK_ACTOR) - index++; - reach_type_t* l_t = reach_type(c->reach, l_type, c->opt); pony_assert(l_t != NULL); + + if(l_t->fields[index].embed) + return gentype_embed_ptr(c, l_t, l_value, index); + compile_type_t* l_c_t = (compile_type_t*)l_t->c_type; - return LLVMBuildStructGEP2(c->builder, l_c_t->structure, l_value, index, ""); + return LLVMBuildStructGEP2(c->builder, l_c_t->structure, l_value, + gentype_field_index(l_t, index), ""); } LLVMValueRef gen_fieldptr(compile_t* c, ast_t* ast) @@ -694,6 +693,7 @@ LLVMValueRef gen_array_const(compile_t* c, ast_t* recover) LLVMSetGlobalConstant(g_inst, true); LLVMSetLinkage(g_inst, LLVMPrivateLinkage); LLVMSetUnnamedAddr(g_inst, true); + codegen_place_in_constant_section(c, g_inst); ast_free_unattached(array_type); return g_inst; @@ -730,6 +730,7 @@ LLVMValueRef gen_string(compile_t* c, ast_t* ast) LLVMSetGlobalConstant(g_inst, true); LLVMSetLinkage(g_inst, LLVMPrivateLinkage); LLVMSetUnnamedAddr(g_inst, true); + codegen_place_in_constant_section(c, g_inst); string = POOL_ALLOC(genned_string_t); string->string = name; diff --git a/src/libponyc/codegen/gentrace.c b/src/libponyc/codegen/gentrace.c index ad69431896b..532fe93ba79 100644 --- a/src/libponyc/codegen/gentrace.c +++ b/src/libponyc/codegen/gentrace.c @@ -9,6 +9,7 @@ #include "../type/matchtype.h" #include "../type/subtype.h" #include "../type/typealias.h" +#include "../../libponyrt/gc/embedflags.h" #include "ponyassert.h" // Arranged from most specific to least specific. @@ -509,29 +510,145 @@ static void trace_nullable_pointer(compile_t* c, LLVMValueRef ctx, LLVMPositionBuilderAtEnd(c->builder, is_true); } -static void trace_known(compile_t* c, LLVMValueRef ctx, LLVMValueRef object, - ast_t* type, int mutability) +void gentrace_known(compile_t* c, LLVMValueRef ctx, LLVMValueRef object, + reach_type_t* t, int mutability) { - reach_type_t* t = reach_type(c->reach, type, c->opt); + compile_type_t* c_t = (compile_type_t*)t->c_type; + + // A Pointer can point at the start of an object of another type, such as a + // struct, and has no trace function. A Pointer is traced as opaque and with + // no type. A non-opaque visit would mark that object's allocation as traced + // without tracing its fields, and a visit with a type would leave the + // Pointer's type in the object map as the type of the object at that + // address. + if(is_pointer(t->ast)) + { + LLVMValueRef args[2]; + args[0] = ctx; + args[1] = object; + gencall_runtime(c, "pony_trace", args, 2, ""); + return; + } LLVMValueRef args[4]; args[0] = ctx; args[1] = object; - args[2] = codegen_resolve_global(c, ((compile_type_t*)t->c_type)->desc); + args[2] = codegen_resolve_global(c, c_t->desc); args[3] = LLVMConstInt(c->i32, mutability, false); - gencall_runtime(c, "pony_traceknown", args, 4, ""); + if((c_t->embed_flags & PONY_EMBED_ROUTED) != 0) + gencall_runtime(c, "pony_traceknown_routed", args, 4, ""); + else + gencall_runtime(c, "pony_traceknown", args, 4, ""); +} + +static void trace_known(compile_t* c, LLVMValueRef ctx, LLVMValueRef object, + ast_t* type, int mutability) +{ + gentrace_known(c, ctx, object, reach_type(c->reach, type, c->opt), + mutability); +} + +// True if an object of this reach type, or of any subtype of an abstract one, +// can share an address with an object of another type (PONY_EMBED_ROUTED). +static bool type_may_be_routed(reach_type_t* t, int depth) +{ + if((((compile_type_t*)t->c_type)->embed_flags & PONY_EMBED_ROUTED) != 0) + return true; + + switch(t->underlying) + { + case TK_UNIONTYPE: + case TK_ISECTTYPE: + case TK_INTERFACE: + case TK_TRAIT: + { + // A bound on the walk, so it ends even if the subtype sets ever contain + // abstract types; past this depth, treat the type as routed. + if(depth > 32) + return true; + + size_t i = HASHMAP_BEGIN; + reach_type_t* sub; + + while((sub = reach_type_cache_next(&t->subtypes, &i)) != NULL) + { + if(type_may_be_routed(sub, depth + 1)) + return true; + } + + return false; + } + + default: + return false; + } +} + +// True if an object traced through a value of this static type can be of a +// type that shares an address with an object of another type +// (PONY_EMBED_ROUTED). Any type it can't resolve or classify counts as true. +static bool may_be_routed(compile_t* c, ast_t* type) +{ + if(type == NULL) + return true; + + switch(ast_id(type)) + { + // A boxed tuple is never embedded, but trace_dynamic traces the box, and + // any element that matches none of the element types, as the enclosing + // type (orig). So a tuple counts as routed when one of its elements can be. + case TK_TUPLETYPE: + case TK_UNIONTYPE: + case TK_ISECTTYPE: + { + for(ast_t* child = ast_child(type); child != NULL; + child = ast_sibling(child)) + { + if(may_be_routed(c, child)) + return true; + } + + return false; + } + + case TK_NOMINAL: + { + reach_type_t* t = reach_type(c->reach, type, c->opt); + return (t == NULL) || type_may_be_routed(t, 0); + } + + case TK_TYPEALIASREF: + { + ast_t* unfolded = typealias_unfold(type); + if(unfolded == NULL) + return true; + + bool routed = may_be_routed(c, unfolded); + ast_free_unattached(unfolded); + return routed; + } + + default: + return true; + } } static void trace_unknown(compile_t* c, LLVMValueRef ctx, LLVMValueRef object, - int mutability) + int mutability, ast_t* type) { LLVMValueRef args[3]; args[0] = ctx; args[1] = object; args[2] = LLVMConstInt(c->i32, mutability, false); - gencall_runtime(c, "pony_traceunknown", args, 3, ""); + // Only a trace that can reach a type sharing an address with an object of + // another type needs the runtime to check the object's descriptor for + // PONY_EMBED_ROUTED. + if(may_be_routed(c, type)) + gencall_runtime(c, "pony_traceunknown_routed", args, 3, ""); + else + gencall_runtime(c, "pony_traceunknown", args, 3, ""); } static ast_t* find_dup(ast_t* original, ast_t* duplicate, ast_t* target) @@ -634,7 +751,7 @@ static void trace_static(compile_t* c, LLVMValueRef ctx, LLVMValueRef object, if(is_known(src_type)) trace_known(c, ctx, object, src_type, mutability); else - trace_unknown(c, ctx, object, mutability); + trace_unknown(c, ctx, object, mutability, src_type); } static void trace_tuple(compile_t* c, LLVMValueRef ctx, LLVMValueRef src_value, @@ -659,7 +776,7 @@ static void trace_tuple(compile_t* c, LLVMValueRef ctx, LLVMValueRef src_value, pony_assert(src_child == NULL && dst_child == NULL); } else { // This is a boxed tuple. Trace the box, then handle the elements. - trace_unknown(c, ctx, dst_value, PONY_TRACE_OPAQUE); + trace_unknown(c, ctx, dst_value, PONY_TRACE_OPAQUE, src_type); // Extract the elements from the original unboxed tuple. pony_assert(LLVMGetTypeKind(LLVMTypeOf(src_value)) == LLVMStructTypeKind); @@ -688,7 +805,10 @@ static void trace_dynamic_union_or_isect(compile_t* c, LLVMValueRef ctx, trace_dynamic(c, ctx, object, child, orig, tuple, next_block); } - // No type matched. This may be a boxed primitive: trace it here. + // No type matched. This may be a boxed primitive: trace it here. The value + // can be any type the enclosing type (orig) allows, so choose between the + // routed and plain call by that type, not by the union or intersection this + // call is walking. if(gentagged_has_any_taggable(c)) { // A tagged pointer has no heap object — skip tracing. @@ -698,7 +818,7 @@ static void trace_dynamic_union_or_isect(compile_t* c, LLVMValueRef ctx, LLVMBuildCondBr(c->builder, is_tagged, skip_block, trace_block); LLVMPositionBuilderAtEnd(c->builder, trace_block); - trace_unknown(c, ctx, object, PONY_TRACE_OPAQUE); + trace_unknown(c, ctx, object, PONY_TRACE_OPAQUE, orig); LLVMBuildBr(c->builder, skip_block); LLVMMoveBasicBlockAfter(skip_block, LLVMGetInsertBlock(c->builder)); @@ -706,7 +826,7 @@ static void trace_dynamic_union_or_isect(compile_t* c, LLVMValueRef ctx, } else { - trace_unknown(c, ctx, object, PONY_TRACE_OPAQUE); + trace_unknown(c, ctx, object, PONY_TRACE_OPAQUE, orig); } } @@ -1032,8 +1152,11 @@ static void trace_dynamic(compile_t* c, LLVMValueRef ctx, LLVMValueRef object, LLVMPositionBuilderAtEnd(c->builder, tuple_block); } - // This is a boxed tuple. Trace the box, then handle the elements. - trace_unknown(c, ctx, object, PONY_TRACE_OPAQUE); + // This is a boxed tuple. Trace the box, then handle the elements. The + // value may also be any other type the enclosing type (orig) allows, so + // choose between the routed and plain call by that type, not the + // tuple's. + trace_unknown(c, ctx, object, PONY_TRACE_OPAQUE, orig); LLVMValueRef desc = gendesc_fetch(c, object); LLVMValueRef ptr = gendesc_ptr_to_fields(c, object, desc); @@ -1318,7 +1441,7 @@ void gentrace(compile_t* c, LLVMValueRef ctx, LLVMValueRef src_value, break; case TRACE_VAL_UNKNOWN: - trace_unknown(c, ctx, dst_value, PONY_TRACE_IMMUTABLE); + trace_unknown(c, ctx, dst_value, PONY_TRACE_IMMUTABLE, src_type); break; case TRACE_MUT_KNOWN: @@ -1326,7 +1449,7 @@ void gentrace(compile_t* c, LLVMValueRef ctx, LLVMValueRef src_value, break; case TRACE_MUT_UNKNOWN: - trace_unknown(c, ctx, dst_value, PONY_TRACE_MUTABLE); + trace_unknown(c, ctx, dst_value, PONY_TRACE_MUTABLE, src_type); break; case TRACE_TAG_KNOWN: @@ -1334,7 +1457,7 @@ void gentrace(compile_t* c, LLVMValueRef ctx, LLVMValueRef src_value, break; case TRACE_TAG_UNKNOWN: - trace_unknown(c, ctx, dst_value, PONY_TRACE_OPAQUE); + trace_unknown(c, ctx, dst_value, PONY_TRACE_OPAQUE, src_type); break; case TRACE_STATIC: diff --git a/src/libponyc/codegen/gentrace.h b/src/libponyc/codegen/gentrace.h index b6d905221d2..69c5da45e07 100644 --- a/src/libponyc/codegen/gentrace.h +++ b/src/libponyc/codegen/gentrace.h @@ -10,6 +10,9 @@ bool gentrace_needed(compile_t* c, ast_t* src_type, ast_t* dst_type); void gentrace_prototype(compile_t* c, reach_type_t* t); +void gentrace_known(compile_t* c, LLVMValueRef ctx, LLVMValueRef object, + reach_type_t* t, int mutability); + void gentrace(compile_t* c, LLVMValueRef ctx, LLVMValueRef src_value, LLVMValueRef dst_value, ast_t* src_type, ast_t* dst_type); diff --git a/src/libponyc/codegen/gentype.c b/src/libponyc/codegen/gentype.c index 39436c0fbd4..98f06456fb4 100644 --- a/src/libponyc/codegen/gentype.c +++ b/src/libponyc/codegen/gentype.c @@ -14,6 +14,7 @@ #include "../type/cap.h" #include "../type/reify.h" #include "../type/subtype.h" +#include "../../libponyrt/gc/embedflags.h" #include "../../libponyrt/mem/pool.h" #include "ponyassert.h" #include @@ -320,6 +321,7 @@ static void make_global_instance(compile_t* c, reach_type_t* t) LLVMSetInitializer(c_t->instance, value); LLVMSetGlobalConstant(c_t->instance, true); LLVMSetLinkage(c_t->instance, LLVMExternalLinkage); + codegen_place_in_constant_section(c, c_t->instance); } static void make_get_behavior_name(compile_t* c, reach_type_t* t) @@ -391,7 +393,6 @@ static bool make_struct(compile_t* c, reach_type_t* t) { compile_type_t* c_t = (compile_type_t*)t->c_type; LLVMTypeRef type; - int extra = 0; bool packed = false; if(t->bare_method != NULL) @@ -433,17 +434,11 @@ static bool make_struct(compile_t* c, reach_type_t* t) return true; } - extra = 1; type = c_t->structure; break; case TK_CLASS: - extra = 1; - type = c_t->structure; - break; - case TK_ACTOR: - extra = 2; type = c_t->structure; break; @@ -452,6 +447,9 @@ static bool make_struct(compile_t* c, reach_type_t* t) return false; } + // A tuple's fields are the elements of its unboxed type (c_t->primitive). + uint32_t extra = + (t->underlying == TK_TUPLETYPE) ? 0 : gentype_field_index(t, 0); size_t buf_size = (t->field_count + extra) * sizeof(LLVMTypeRef); LLVMTypeRef* elements = (LLVMTypeRef*)ponyint_pool_alloc_size(buf_size); @@ -484,6 +482,15 @@ static bool make_struct(compile_t* c, reach_type_t* t) return true; } +static bool embed_has_no_size(compile_t* c, reach_type_t* t, uint32_t i) +{ + if(!t->fields[i].embed) + return false; + + compile_type_t* f_c_t = (compile_type_t*)t->fields[i].type->c_type; + return LLVMABISizeOfType(c->target_data, f_c_t->structure) == 0; +} + static LLVMMetadataRef make_debug_field(compile_t* c, reach_type_t* t, uint32_t i) { @@ -504,15 +511,8 @@ static LLVMMetadataRef make_debug_field(compile_t* c, reach_type_t* t, if(is_name_private(name)) flags = (LLVMDIFlags)(flags | LLVMDIFlagPrivate); - uint32_t extra = 0; - - if(t->underlying != TK_STRUCT) - extra++; - - if(t->underlying == TK_ACTOR) - extra++; - - offset = LLVMOffsetOfElement(c->target_data, c_t->structure, i + extra); + offset = LLVMOffsetOfElement(c->target_data, c_t->structure, + gentype_field_index(t, i)); } else { snprintf(buf, 32, "_%d", i + 1); name = buf; @@ -536,6 +536,9 @@ static LLVMMetadataRef make_debug_field(compile_t* c, reach_type_t* t, uint64_t size = LLVMABISizeOfType(c->target_data, type); uint64_t align = LLVMABIAlignmentOfType(c->target_data, type); + if(embed_has_no_size(c, t, i)) + offset = 0; + return LLVMDIBuilderCreateMemberType(c->di, c->di_unit, name, strlen(name), c_t->di_file, (unsigned)ast_line(ast), 8 * size, (uint32_t)(8 * align), 8 * offset, flags, di_type); @@ -678,38 +681,27 @@ static bool make_trace(compile_t* c, reach_type_t* t) LLVMValueRef ctx = LLVMGetParam(c_t->trace_fn, 0); LLVMValueRef object = LLVMGetParam(c_t->trace_fn, 1); - int extra = 0; - LLVMTypeRef structure = c_t->structure; - switch(t->underlying) - { - case TK_CLASS: - extra = 1; // Type descriptor. - break; - - case TK_ACTOR: - extra = 2; // Type descriptor and pad. - break; + bool boxed_tuple = t->underlying == TK_TUPLETYPE; - case TK_TUPLETYPE: - // Skip over the box's descriptor now. It avoids multi-level GEPs later. - object = LLVMBuildStructGEP2(c->builder, c_t->structure, object, 1, ""); - structure = c_t->primitive; - break; - - default: {} + if(boxed_tuple) + { + // Skip over the box's descriptor now. It avoids multi-level GEPs later. + object = LLVMBuildStructGEP2(c->builder, c_t->structure, object, 1, ""); + structure = c_t->primitive; } for(uint32_t i = 0; i < t->field_count; i++) { reach_field_t* f = &t->fields[i]; compile_type_t* f_c_t = (compile_type_t*)f->type->c_type; - LLVMValueRef field = LLVMBuildStructGEP2(c->builder, structure, object, - i + extra, ""); if(!f->embed) { // Call the trace function indirectly depending on rcaps. + uint32_t index = boxed_tuple ? i : gentype_field_index(t, i); + LLVMValueRef field = LLVMBuildStructGEP2(c->builder, structure, object, + index, ""); field = LLVMBuildLoad2(c->builder, f_c_t->mem_type, field, ""); ast_t* field_type = f->ast; field = gen_assign_cast(c, f_c_t->use_type, field, field_type); @@ -724,7 +716,7 @@ static bool make_trace(compile_t* c, reach_type_t* t) LLVMTypeRef trace_fn_type = LLVMGlobalGetValueType(trace_fn); LLVMValueRef args[2]; args[0] = ctx; - args[1] = field; + args[1] = gentype_embed_ptr(c, t, object, i); LLVMBuildCall2(c->builder, trace_fn_type, trace_fn, args, 2, ""); } @@ -736,6 +728,120 @@ static bool make_trace(compile_t* c, reach_type_t* t) return true; } +// Sets a flag on every type embedded in t, directly or through other embedded +// objects. +static void flag_embedded(reach_type_t* t, uint8_t flag) +{ + for(uint32_t i = 0; i < t->field_count; i++) + { + if(!t->fields[i].embed) + continue; + + compile_type_t* f_c_t = (compile_type_t*)t->fields[i].type->c_type; + + if((f_c_t->embed_flags & flag) == 0) + { + f_c_t->embed_flags |= flag; + flag_embedded(t->fields[i].type, flag); + } + } +} + +LLVMValueRef gentype_embed_ptr(compile_t* c, reach_type_t* t, + LLVMValueRef object, uint32_t index) +{ + pony_assert(t->fields[index].embed); + + // A field with no size stores nothing, and its position can be the end of + // the object, which is the address of whatever is allocated after it, so it + // takes the object's address. + if(embed_has_no_size(c, t, index)) + return object; + + compile_type_t* c_t = (compile_type_t*)t->c_type; + return LLVMBuildStructGEP2(c->builder, c_t->structure, object, + gentype_field_index(t, index), ""); +} + +uint32_t gentype_field_index(reach_type_t* t, uint32_t index) +{ + if(t->underlying != TK_STRUCT) + index++; + + if(t->underlying == TK_ACTOR) + index++; + + return index; +} + +reach_type_t* gentype_first_embed(compile_t* c, reach_type_t* t) +{ + if(t->underlying != TK_STRUCT) + return NULL; + + compile_type_t* c_t = (compile_type_t*)t->c_type; + + // A struct has no header, so an embedded field at offset 0 shares the + // struct's address. Fields with no size can also sit at offset 0; the one + // with a non-zero size is the object that starts the struct. + for(uint32_t i = 0; i < t->field_count; i++) + { + if(LLVMOffsetOfElement(c->target_data, c_t->structure, i) != 0) + return NULL; + + if(t->fields[i].embed && !embed_has_no_size(c, t, i)) + return t->fields[i].type; + } + + return NULL; +} + +// Records the PONY_EMBED_* flags (gc/embedflags.h) of each type. +static void compute_embed_flags(compile_t* c) +{ + size_t i = HASHMAP_BEGIN; + reach_type_t* t; + + while((t = reach_types_next(&c->reach->types, &i)) != NULL) + { + compile_type_t* c_t = (compile_type_t*)t->c_type; + + for(uint32_t f = 0; f < t->field_count; f++) + { + if(!t->fields[f].embed) + continue; + + compile_type_t* f_c_t = (compile_type_t*)t->fields[f].type->c_type; + + if(t->underlying == TK_ACTOR) + c_t->embed_flags |= PONY_EMBED_ACTOR_LOOKUP; + + if(embed_has_no_size(c, t, f)) + { + // A field with no size has the address of the object that holds it + // (see gentype_embed_ptr), so the two share an address. + f_c_t->embed_flags |= PONY_EMBED_ROUTED; + + if(t->underlying != TK_ACTOR) + c_t->embed_flags |= PONY_EMBED_ROUTED; + } + } + + if(t->underlying == TK_ACTOR) + flag_embedded(t, PONY_EMBED_IN_ACTOR); + + reach_type_t* first = gentype_first_embed(c, t); + + if(first != NULL) + { + // The struct and its first embedded field share an address. + c_t->embed_flags |= PONY_EMBED_ROUTED; + ((compile_type_t*)first->c_type)->embed_flags |= + PONY_EMBED_ROUTED | PONY_EMBED_AT_START; + } + } +} + static void switch_to_type_module(compile_t* c, reach_type_t* t) { if(c->per_module_count > 0) @@ -832,6 +938,9 @@ bool gentypes(compile_t* c) return false; } + // Before any trace is generated, and after sizes are known. + compute_embed_flags(c); + if(c->opt->verbosity >= VERBOSITY_INFO) fprintf(stderr, " Functions\n"); diff --git a/src/libponyc/codegen/gentype.h b/src/libponyc/codegen/gentype.h index e3997b13e68..c289f651684 100644 --- a/src/libponyc/codegen/gentype.h +++ b/src/libponyc/codegen/gentype.h @@ -32,10 +32,28 @@ typedef struct compile_type_t LLVMMetadataRef di_file; LLVMMetadataRef di_type; LLVMMetadataRef di_type_embed; + + // PONY_EMBED_* flags, set before any trace is generated. + uint8_t embed_flags; } compile_type_t; bool gentypes(compile_t* c); +// The index in t's LLVM structure of t's field at index: every type but a +// struct has its descriptor first, and an actor also has a pad. A boxed tuple's +// structure is its descriptor and then the unboxed tuple (c_t->primitive), so +// for a tuple, index 0 gives the unboxed tuple. +uint32_t gentype_field_index(reach_type_t* t, uint32_t index); + +// The address of an embedded field of t in object. A field with no size has +// the address of the object that holds it. +LLVMValueRef gentype_embed_ptr(compile_t* c, reach_type_t* t, + LLVMValueRef object, uint32_t index); + +// For a struct that starts with an embedded field with a non-zero size, the +// type of that field, which shares the struct's address. NULL otherwise. +reach_type_t* gentype_first_embed(compile_t* c, reach_type_t* t); + PONY_EXTERN_C_END #endif diff --git a/src/libponylto/README.md b/src/libponylto/README.md index b880970e6e7..09dbbf689bb 100644 --- a/src/libponylto/README.md +++ b/src/libponylto/README.md @@ -10,9 +10,9 @@ lld loads the passes through LLVM's static plugin mechanism: `Extension.def` dec - **OptimizeGcCalls** and **LowerGcMaps** preserve the ordinary call for methods proved allocation-free and emit return-address maps for supported scalar calls on optimized Linux AMD64. Where a call needs local roots and has no native map, the caller passes a compiler-generated record. A caller with no local roots forwards its parent frame. -- **HeapToStack** (`heap_to_stack.cc`): Promotes `pony_alloc` and `pony_alloc_small` calls to stack allocations when the allocated object does not escape the function. Runs as a CGSCC pass so it sees the call graph after cross-module inlining. +- **HeapToStack** (`heap_to_stack.cc`): Promotes `pony_alloc`, `pony_alloc_small` and `pony_alloc_small_shared_start` calls to stack allocations when the allocated object does not escape the function. Runs as a CGSCC pass so it sees the call graph after cross-module inlining. -- **InlineRemainingAllocPass** (`plugin.cc`): Strips noinline from `pony_alloc` and `pony_alloc_small` and inlines the remaining call sites after HeapToStack has run. Those functions carry noinline (actor.c) so the CGSCC inliner preserves the call sites HeapToStack needs; this pass cleans up afterward. +- **InlineRemainingAllocPass** (`plugin.cc`): Strips noinline from `pony_alloc`, `pony_alloc_small` and `pony_alloc_small_shared_start` and inlines the remaining call sites after HeapToStack has run. Those functions carry noinline (actor.c) so the CGSCC inliner preserves the call sites HeapToStack needs; this pass cleans up afterward. - **NoAllocCheck** (`noalloc_check.cc`): Reports an error for each function marked `\noalloc\` that can allocate, send a message, create an actor, or make an FFI call or an indirect call. It follows calls into other functions. It runs after HeapToStack, so an allocation that HeapToStack moves to the stack does not count. diff --git a/src/libponylto/heap_to_stack.cc b/src/libponylto/heap_to_stack.cc index 48c3ee1edf0..5cc60b4d797 100644 --- a/src/libponylto/heap_to_stack.cc +++ b/src/libponylto/heap_to_stack.cc @@ -26,8 +26,9 @@ STATISTIC(NumStackAlloc, "Number of allocations promoted to stack"); static constexpr unsigned HEAP_MINBITS = 5; // The alloca's alignment must match the runtime's heap guarantee. The -// `align` attribute on pony_alloc/pony_alloc_small carries that value; -// it is set in init_runtime_decls (codegen.c). +// `align` attribute on pony_alloc, pony_alloc_small and +// pony_alloc_small_shared_start carries that value; it is set in +// set_runtime_attrs (codegen.c). static void printTransform(Instruction *i, const char *s) { @@ -159,8 +160,11 @@ bool HeapToStack::runOnInstruction(IRBuilder<> &builder, Instruction *inst, if(fun->getName().compare("pony_alloc") == 0) { } - else if(fun->getName().compare("pony_alloc_small") == 0) + else if((fun->getName().compare("pony_alloc_small") == 0) || + (fun->getName().compare("pony_alloc_small_shared_start") == 0)) { + // Memory on the stack has no heap chunk, so a struct that starts with an + // embedded field and is allocated on the stack needs no shared-start bit. small = true; } else diff --git a/src/libponylto/noalloc_check.cc b/src/libponylto/noalloc_check.cc index a0e2a4b8023..65dea0e4b7f 100644 --- a/src/libponylto/noalloc_check.cc +++ b/src/libponylto/noalloc_check.cc @@ -13,6 +13,8 @@ static const char* const alloc_names[] = { "pony_alloc", "pony_alloc_small", "pony_alloc_large", + "pony_alloc_small_shared_start", + "pony_alloc_large_shared_start", "pony_alloc_final", "pony_alloc_small_final", "pony_alloc_large_final", diff --git a/src/libponylto/plugin.cc b/src/libponylto/plugin.cc index 18cd4ef2e6c..de771bb43c8 100644 --- a/src/libponylto/plugin.cc +++ b/src/libponylto/plugin.cc @@ -14,9 +14,9 @@ using namespace llvm; namespace pony { -// After HeapToStack has run, strip noinline from pony_alloc and -// pony_alloc_small and inline the remaining call sites. These functions -// carry noinline (actor.c) so HeapToStack can match them by name at +// After HeapToStack has run, strip noinline from pony_alloc, pony_alloc_small +// and pony_alloc_small_shared_start and inline the remaining call sites. These +// functions carry noinline (actor.c) so HeapToStack can match them by name at // call sites. class InlineRemainingAllocPass : public PassInfoMixin @@ -24,9 +24,10 @@ class InlineRemainingAllocPass public: PreservedAnalyses run(Module &M, ModuleAnalysisManager &) { - SmallVector targets; + SmallVector targets; - for(auto *name : {"pony_alloc", "pony_alloc_small"}) + for(auto *name : + {"pony_alloc", "pony_alloc_small", "pony_alloc_small_shared_start"}) { if(Function *F = M.getFunction(name)) targets.push_back(F); diff --git a/src/libponyrt/CMakeLists.txt b/src/libponyrt/CMakeLists.txt index 3079371dc1b..a85a22257ad 100644 --- a/src/libponyrt/CMakeLists.txt +++ b/src/libponyrt/CMakeLists.txt @@ -20,6 +20,7 @@ set(_c_src gc/delta.c gc/gc.c gc/frames.c + gc/sections.c gc/marklocal.c gc/objectmap.c gc/trace.c diff --git a/src/libponyrt/actor/actor.c b/src/libponyrt/actor/actor.c index 82170e67416..be7d129c552 100644 --- a/src/libponyrt/actor/actor.c +++ b/src/libponyrt/actor/actor.c @@ -5,7 +5,10 @@ #include "../sched/scheduler.h" #include "../sched/cpu.h" #include "../mem/pool.h" +#include "../mem/pagemap.h" #include "../gc/cycle.h" +#include "../gc/sections.h" +#include "../gc/embedflags.h" #include "../gc/trace.h" #include "../tracing/tracing.h" #include "ponyassert.h" @@ -796,6 +799,48 @@ bool ponyint_actor_run(pony_ctx_t* ctx, pony_actor_t* actor) return !ponyint_messageq_markempty(&actor->q); } +// Whether the actors of an actor type with an embedded field need the pagemap +// for their lookup whatever their size, because ponyint_actor_in_pool can't +// find them: the memalign pool can't find an allocation's start, and the arena +// pool needs the type's descriptor in the descriptor section. +static bool lookup_needs_pagemap(pony_type_t* type) +{ + if((type->embed_flags & PONY_EMBED_ACTOR_LOOKUP) == 0) + return false; + +#ifdef POOL_USE_ARENA + return !ponyint_desc_section_holds(type); +#else + return true; +#endif +} + +// An actor recorded in the pagemap is given at least a whole pagemap entry, so +// no other allocation shares it. +static size_t actor_request_size(pony_type_t* type) +{ + if(lookup_needs_pagemap(type) && (type->size < POOL_ALIGN)) + return POOL_ALIGN; + + return type->size; +} + +// The size of the pool block that holds an actor of this type. +static size_t actor_pool_size(pony_type_t* type) +{ + return ponyint_pool_used_size(actor_request_size(type)); +} + +// Whether an actor of this type has its allocation recorded in the pagemap. +static bool actors_of_type_in_pagemap(pony_type_t* type) +{ + if((type->embed_flags & PONY_EMBED_ACTOR_LOOKUP) == 0) + return false; + + return lookup_needs_pagemap(type) || + !ponyint_pool_size_in_arena(actor_request_size(type)); +} + void ponyint_actor_destroy(pony_actor_t* actor, actor_destroyed_reason_t reason) { pony_assert(has_sync_flag(actor, ACTOR_SYNC_FLAG_PENDINGDESTROY)); @@ -822,7 +867,7 @@ void ponyint_actor_destroy(pony_actor_t* actor, actor_destroyed_reason_t reason) #ifdef USE_RUNTIMESTATS pony_ctx_t* ctx = pony_ctx(); ctx->schedulerstats.mem_used_actors -= actor->type->size; - ctx->schedulerstats.mem_allocated_actors -= ponyint_pool_used_size(actor->type->size); + ctx->schedulerstats.mem_allocated_actors -= ponyint_actor_alloc_size(actor); ctx->schedulerstats.destroyed_actors_counter++; if (ponyint_sched_print_stats()) print_actor_stats(actor); @@ -831,8 +876,18 @@ void ponyint_actor_destroy(pony_actor_t* actor, actor_destroyed_reason_t reason) (void)reason; TRACING_ACTOR_DESTROYED(actor, reason); + size_t request_size = actor_request_size(actor->type); + + // Forget the actor's pagemap entries before its memory can be reused. + if(actors_of_type_in_pagemap(actor->type)) + ponyint_pagemap_set_bulk(actor, NULL, NULL, actor_pool_size(actor->type)); + + // ponyint_actor_in_pool treats a pool block whose first word is an actor + // descriptor as an actor, so clear the descriptor before the block is freed. + actor->type = NULL; + // Free variable sized actors correctly. - ponyint_pool_free_size(actor->type->size, actor); + ponyint_pool_free_size(request_size, actor); } gc_t* ponyint_actor_gc(pony_actor_t* actor) @@ -898,16 +953,43 @@ bool ponyint_actor_getnoblock() return actor_noblock; } +pony_actor_t* ponyint_actor_in_pool(void* p) +{ + void* base = ponyint_pool_base(p); + + if(base != NULL) + { + // The block may not be an actor: FFI code can pass pool memory to Pony, + // and a freed actor's block can be handed out again (ponyint_actor_destroy + // clears its descriptor word). These checks reject a freed block; actor.h + // says which pool memory from C they accept. + pony_type_t* t = *(pony_type_t**)base; + + if((((uintptr_t)t % sizeof(void*)) == 0) && + ponyint_desc_section_holds(t) && + (t->dispatch != NULL) && + ((t->embed_flags & PONY_EMBED_ACTOR_LOOKUP) != 0) && + ((char*)p < ((char*)base + t->size))) + return (pony_actor_t*)base; + } + + return NULL; +} + PONY_API pony_actor_t* pony_create(pony_ctx_t* ctx, pony_type_t* type, bool orphaned) { pony_assert(type != NULL); // allocate variable sized actors correctly - pony_actor_t* actor = (pony_actor_t*)ponyint_pool_alloc_size(type->size); + size_t request_size = actor_request_size(type); + pony_actor_t* actor = (pony_actor_t*)ponyint_pool_alloc_size(request_size); memset(actor, 0, type->size); actor->type = type; + if(actors_of_type_in_pagemap(type)) + ponyint_pagemap_set_bulk(actor, NULL, actor, actor_pool_size(type)); + #ifdef USE_SYSTEMATIC_TESTING // Assign a stable, monotonic creation-order id (ids start at 1; 0 is never a // valid actor id). Used to order otherwise pointer-ordered scheduling @@ -919,7 +1001,7 @@ PONY_API pony_actor_t* pony_create(pony_ctx_t* ctx, pony_type_t* type, #ifdef USE_RUNTIMESTATS ctx->schedulerstats.mem_used_actors += type->size; - ctx->schedulerstats.mem_allocated_actors += ponyint_pool_used_size(type->size); + ctx->schedulerstats.mem_allocated_actors += ponyint_actor_alloc_size(actor); ctx->schedulerstats.created_actors_counter++; #endif @@ -1152,12 +1234,12 @@ void ponyint_sendi_inject(pony_actor_t* to, uint32_t id, intptr_t i) ponyint_sendv_inject(to, &m->msg); } -// HeapToStack (libponylto) matches pony_alloc and pony_alloc_small by name -// at call sites to promote heap allocations to the stack. With -O2 bitcode -// the CGSCC inliner would inline these before HeapToStack runs, removing the -// call sites HeapToStack needs. noinline preserves them through the inliner; -// InlineRemainingAllocPass (plugin.cc) strips it afterward and inlines the -// surviving calls. +// HeapToStack (libponylto) matches pony_alloc, pony_alloc_small and +// pony_alloc_small_shared_start by name at call sites to promote heap +// allocations to the stack. With -O2 bitcode the CGSCC inliner would inline +// these before HeapToStack runs, removing the call sites HeapToStack needs. +// noinline preserves them through the inliner; InlineRemainingAllocPass +// (plugin.cc) strips it afterward and inlines the surviving calls. PONY_API PONY_NOINLINE void* pony_alloc(pony_ctx_t* ctx, size_t size) { @@ -1184,6 +1266,23 @@ PONY_API void* pony_alloc_large(pony_ctx_t* ctx, size_t size) TRACK_NO_FINALISERS); } +PONY_API PONY_NOINLINE +void* pony_alloc_small_shared_start(pony_ctx_t* ctx, uint32_t sizeclass) +{ + pony_assert(ctx->current != NULL); + + return ponyint_heap_alloc_small_shared_start(ctx->current, + &ctx->current->heap, sizeclass); +} + +PONY_API void* pony_alloc_large_shared_start(pony_ctx_t* ctx, size_t size) +{ + pony_assert(ctx->current != NULL); + + return ponyint_heap_alloc_large_shared_start(ctx->current, + &ctx->current->heap, size); +} + PONY_API void* pony_realloc(pony_ctx_t* ctx, void* p, size_t size, size_t copy) { pony_assert(ctx->current != NULL); @@ -1279,7 +1378,7 @@ size_t ponyint_actor_mem_size(pony_actor_t* actor) size_t ponyint_actor_alloc_size(pony_actor_t* actor) { - return ponyint_pool_used_size(actor->type->size); + return actor_pool_size(actor->type); } size_t ponyint_actor_total_mem_size(pony_actor_t* actor) @@ -1308,7 +1407,7 @@ size_t ponyint_actor_total_alloc_size(pony_actor_t* actor) // allocation for actor struct size (maybe this shouldn't be counted to // avoid double counting since it is counted as part of the scheduler // thread mem allocated?) - ponyint_pool_used_size(actor->type->size) + ponyint_actor_alloc_size(actor) // cycle detector memory allocated (or 0 if not cycle detector) + ( ponyint_is_cycle(actor) ? ponyint_cycle_alloc_size() : 0) // actor heap memory allocated diff --git a/src/libponyrt/actor/actor.h b/src/libponyrt/actor/actor.h index cae7477e920..b468f089ee8 100644 --- a/src/libponyrt/actor/actor.h +++ b/src/libponyrt/actor/actor.h @@ -191,6 +191,15 @@ void ponyint_actor_destroy(pony_actor_t* actor, actor_destroyed_reason_t reason) gc_t* ponyint_actor_gc(pony_actor_t* actor); +// The actor whose pool allocation contains p, if its type has an embedded +// field; otherwise NULL. Returns NULL for an actor that pony_create recorded in +// the pagemap; ponyint_pagemap_get finds those. p must point into a live +// allocation or outside the pool. A pool block that isn't an actor can be +// returned only if its first word is an address with a whole descriptor's +// bytes in the descriptor section, and those bytes, read as a descriptor, have +// a dispatch function, PONY_EMBED_ACTOR_LOOKUP and a size that reaches p. +pony_actor_t* ponyint_actor_in_pool(void* p); + heap_t* ponyint_actor_heap(pony_actor_t* actor); bool ponyint_actor_is_pinned(pony_actor_t* actor); diff --git a/src/libponyrt/gc/cycle.c b/src/libponyrt/gc/cycle.c index 246ff38ebd3..d4c80e22762 100644 --- a/src/libponyrt/gc/cycle.c +++ b/src/libponyrt/gc/cycle.c @@ -1482,6 +1482,7 @@ static pony_type_t cycle_type = cycle_dispatch, NULL, 0, + false, 0, NULL, NULL, diff --git a/src/libponyrt/gc/embedflags.h b/src/libponyrt/gc/embedflags.h new file mode 100644 index 00000000000..42e85772a10 --- /dev/null +++ b/src/libponyrt/gc/embedflags.h @@ -0,0 +1,21 @@ +#ifndef gc_embedflags_h +#define gc_embedflags_h + +/* The flags the compiler records in pony_type_t's embed_flags. + * + * PONY_EMBED_ROUTED: the type is routed (pony.h, at pony_traceknown): an object + * of the type can share its address with an object of another type. Traces of + * it go through pony_traceknown_routed or pony_traceunknown_routed. + * PONY_EMBED_IN_ACTOR: an object of the type can be inside an actor. + * PONY_EMBED_ACTOR_LOOKUP: the type is an actor with an embedded field, so the + * runtime must be able to find the actor from the address of that field. + * PONY_EMBED_AT_START: the type is embedded as the first field with a non-zero + * size of some struct, so it can share the start of an allocation of another + * type. + */ +#define PONY_EMBED_ROUTED 0x01 +#define PONY_EMBED_IN_ACTOR 0x02 +#define PONY_EMBED_ACTOR_LOOKUP 0x04 +#define PONY_EMBED_AT_START 0x08 + +#endif diff --git a/src/libponyrt/gc/gc.c b/src/libponyrt/gc/gc.c index a4f9ba4b5b9..551b02a6733 100644 --- a/src/libponyrt/gc/gc.c +++ b/src/libponyrt/gc/gc.c @@ -4,19 +4,33 @@ #include "../mem/pagemap.h" #include "../mem/pool.h" #include "../tracing/tracing.h" +#include "sections.h" +#include "embedflags.h" #include "ponyassert.h" #include #ifdef USE_SYSTEMATIC_TESTING #include #endif +// The send, receive and remote mark functions below take routed: whether the +// type can share an address with an object of another type +// (PONY_EMBED_ROUTED). Pass it as a constant: inlining each call drops the +// checks that the constant rules out, so the plain and routed dispatchers each +// get their own version. + #define GC_IMMUT_HEAP_EQUIV 1024 DEFINE_STACK(ponyint_gcstack, gcstack_t, void); -static bool might_reference_actor(pony_type_t* t) +// Whether every holder of an object of this type traces the object's fields +// itself, so it is never an immutable root. An owner traces an immutable root +// as the type its object map records, and for an address shared by a struct +// and the field at its start, that can be the field's type from an earlier +// epoch. +static bool traced_by_holders(pony_type_t* t) { - return t != NULL && t->might_reference_actor; + return (t != NULL) && (t->might_reference_actor || + ((t->embed_flags & PONY_EMBED_ROUTED) != 0)); } static void acquire_actor(pony_ctx_t* ctx, pony_actor_t* actor) @@ -36,6 +50,98 @@ static void acquire_object(pony_ctx_t* ctx, pony_actor_t* actor, obj->immutable = source->immutable; } +#define GC_VISITS_MIN 64 + +static size_t visit_slot(gc_visitset_t* set, void* p, pony_type_t* t) +{ + size_t mask = set->capacity - 1; + size_t i = (ponyint_hash_ptr(p) ^ ponyint_hash_ptr(t)) & mask; + + while((set->slots[i].address != NULL) && + ((set->slots[i].address != p) || (set->slots[i].type != t))) + i = (i + 1) & mask; + + return i; +} + +static void visits_resize(gc_visitset_t* set, size_t capacity) +{ + gc_visit_t* old = set->slots; + size_t old_capacity = set->capacity; + + set->slots = + (gc_visit_t*)ponyint_pool_alloc_size(capacity * sizeof(gc_visit_t)); + memset(set->slots, 0, capacity * sizeof(gc_visit_t)); + set->capacity = capacity; + + for(size_t i = 0; i < old_capacity; i++) + { + if(old[i].address != NULL) + set->slots[visit_slot(set, old[i].address, old[i].type)] = old[i]; + } + + if(old != NULL) + ponyint_pool_free_size(old_capacity * sizeof(gc_visit_t), old); +} + +// Records that this mark visited p as t. True on the first visit. +static bool first_visit(pony_ctx_t* ctx, void* p, pony_type_t* t) +{ + gc_visitset_t* set = &ctx->visits; + pony_assert(p != NULL); + + if((set->count + 1) * 2 > set->capacity) + visits_resize(set, + (set->capacity == 0) ? GC_VISITS_MIN : set->capacity * 2); + + size_t i = visit_slot(set, p, t); + if(set->slots[i].address != NULL) + return false; + + set->slots[i].address = p; + set->slots[i].type = t; + set->count++; + return true; +} + +void ponyint_gc_free_visits(pony_ctx_t* ctx) +{ + gc_visitset_t* set = &ctx->visits; + + if(set->slots != NULL) + ponyint_pool_free_size(set->capacity * sizeof(gc_visit_t), set->slots); + + memset(set, 0, sizeof(*set)); +} + +void ponyint_gc_end_visits(pony_ctx_t* ctx) +{ + gc_visitset_t* set = &ctx->visits; + + if((set->capacity > GC_VISITS_MIN) && (set->count * 8 < set->capacity)) + { + ponyint_gc_free_visits(ctx); + return; + } + + if(set->count != 0) + { + memset(set->slots, 0, set->capacity * sizeof(gc_visit_t)); + set->count = 0; + } +} + +// The amount added to this actor's heap use, to provoke a collection, for an +// object another actor owns: the size of its heap chunk, or the type's size +// when the object is inside an actor's own allocation and has no chunk. +static size_t foreign_size(chunk_t* chunk, pony_type_t* t) +{ + if(chunk != NULL) + return ponyint_heap_size(chunk); + + return t->size; +} + static void recurse(pony_ctx_t* ctx, void* p, void* f) { if(f != NULL) @@ -117,6 +223,65 @@ static bool acquire_immutable(pony_ctx_t* ctx, pony_actor_t* actor, return true; } +// True when u is embedded at the start of t, directly or through other +// embedded objects, so the two share an address and t's trace covers u. t must +// be routed: only classes and structs are, and their instance slots hold a +// type or NULL, where a primitive's holds its own instance. +static bool embeds_at_start(pony_type_t* t, pony_type_t* u) +{ + pony_assert((t->embed_flags & PONY_EMBED_ROUTED) != 0); + + for(pony_type_t* x = (pony_type_t*)t->instance; x != NULL; + x = (pony_type_t*)x->instance) + { + if(x == u) + return true; + } + + return false; +} + +// A struct that starts with an embedded field with a non-zero size shares its +// address and its object-map entry with that field. Within one trace epoch, a +// visit as a type that encloses the type already traced there traces the +// object again as the enclosing type, and records that type as the one traced +// there. The receiver's visits are a subset of the sender's (a sender that held +// an object mutably and sends it as val traces its fields; the receiver +// doesn't), and both decide by this rule, so every enclosing type the receiver +// traces again, the sender traced too. +static bool retrace_enclosing(object_t* obj, pony_type_t* t, int mutability) +{ + if((mutability == PONY_TRACE_OPAQUE) || (obj->type == t) || + (obj->type == NULL) || !embeds_at_start(t, obj->type)) + return false; + + obj->type = t; + return true; +} + +// Records the type a non-opaque visit traces with in this epoch. +static void note_traced_type(object_t* obj, pony_type_t* t, int mutability) +{ + if(mutability != PONY_TRACE_OPAQUE) + obj->type = t; +} + +// Whether a visit goes on after begin_visit. visit says whether this epoch has +// already counted the object's references, and it stays VISIT_SKIP when a +// routed visit traces the object again as an enclosing type, so a caller that +// counts by visit doesn't count twice; the result says only whether to trace. +static PONY_FORCEINLINE bool continue_visit(object_t* obj, pony_type_t* t, + int mutability, visit_t visit, bool routed) +{ + if(visit == VISIT_SKIP) + return routed && retrace_enclosing(obj, t, mutability); + + if(routed) + note_traced_type(obj, t, mutability); + + return true; +} + static void send_local_actor(gc_t* gc) { // Increment the current actor rc if it hasn't been yet. @@ -200,14 +365,14 @@ static void mark_remote_actor(pony_ctx_t* ctx, gc_t* gc, actorref_t* aref) } } -static void send_local_object(pony_ctx_t* ctx, void* p, pony_type_t* t, - int mutability) +static PONY_FORCEINLINE void send_local_object(pony_ctx_t* ctx, void* p, + pony_type_t* t, int mutability, bool routed) { gc_t* gc = ponyint_actor_gc(ctx->current); object_t* obj = ponyint_objectmap_getorput(&gc->local, p, t); visit_t visit = begin_visit(gc, obj, mutability); - if(visit == VISIT_SKIP) + if(!continue_visit(obj, t, mutability, visit, routed)) return; if(visit == VISIT_FIRST) @@ -223,12 +388,12 @@ static void send_local_object(pony_ctx_t* ctx, void* p, pony_type_t* t, if(mutability == PONY_TRACE_IMMUTABLE) obj->immutable = true; - if(!obj->immutable || might_reference_actor(t)) + if(!obj->immutable || traced_by_holders(t)) recurse(ctx, p, t->trace); } -static void recv_local_object(pony_ctx_t* ctx, void* p, pony_type_t* t, - int mutability) +static PONY_FORCEINLINE void recv_local_object(pony_ctx_t* ctx, void* p, + pony_type_t* t, int mutability, bool routed) { // get the object size_t index = HASHMAP_UNKNOWN; @@ -239,7 +404,7 @@ static void recv_local_object(pony_ctx_t* ctx, void* p, pony_type_t* t, obj->type = t; visit_t visit = begin_visit(gc, obj, mutability); - if(visit == VISIT_SKIP) + if(!continue_visit(obj, t, mutability, visit, routed)) return; if(visit == VISIT_FIRST) @@ -255,7 +420,17 @@ static void recv_local_object(pony_ctx_t* ctx, void* p, pony_type_t* t, if(mutability == PONY_TRACE_IMMUTABLE) obj->immutable = true; - if(!obj->immutable || might_reference_actor(t)) + if(!obj->immutable || traced_by_holders(t)) + recurse(ctx, p, t->trace); +} + +// A visit the allocation's mark and shallow mark can't record +// (HEAP_MARK_SHARED_START or HEAP_MARK_INTERIOR). The visit is recorded by +// address and type. +static PONY_NOINLINE void mark_local_visit(pony_ctx_t* ctx, void* p, + pony_type_t* t) +{ + if((t->trace != NULL) && first_visit(ctx, p, t)) recurse(ctx, p, t->trace); } @@ -264,9 +439,29 @@ static void mark_local_object(pony_ctx_t* ctx, chunk_t* chunk, void* p, { if(mutability != PONY_TRACE_OPAQUE) { - // Mark in our heap and recurse if it wasn't already marked. - if(!ponyint_heap_mark(chunk, p)) - recurse(ctx, p, t->trace); + switch(ponyint_heap_mark_plain(chunk, p)) + { + case HEAP_MARK_NEW: + case HEAP_MARK_INTERIOR_FIRST: + recurse(ctx, p, t->trace); + return; + + case HEAP_MARK_INTERIOR: + // A repeat visit inside an unmarked allocation, as through an object + // embedded in it, is recorded so a cycle through embedded objects + // ends. + mark_local_visit(ctx, p, t); + return; + + case HEAP_MARK_MARKED: + case HEAP_MARK_COVERED: + return; + + case HEAP_MARK_SHARED_START_FIRST: + case HEAP_MARK_SHARED_START: + pony_assert(0); + return; + } } else { // Do a shallow mark. If the same address is later marked as something that // is not opaque, it will recurse. @@ -274,8 +469,59 @@ static void mark_local_object(pony_ctx_t* ctx, chunk_t* chunk, void* p, } } -static void send_remote_object(pony_ctx_t* ctx, pony_actor_t* actor, - void* p, pony_type_t* t, int mutability) +// A visit to a type that can share an address with an object of another type, +// in this actor's own heap or its own allocation (no chunk). Kept out of line: +// inlined into the routed mark, it makes each routed visit slower. +static PONY_NOINLINE void mark_local_object_routed(pony_ctx_t* ctx, + chunk_t* chunk, void* p, pony_type_t* t, int mutability) +{ + // Every mark of this actor runs the actor's own trace, which traces its + // embedded fields in place. + if(chunk == NULL) + return; + + if(mutability == PONY_TRACE_OPAQUE) + { + // Do a shallow mark. If the same address is later marked as something that + // is not opaque, it will recurse. + ponyint_heap_mark_shallow(chunk, p); + return; + } + + // Only a type embedded at the start of a struct, or a field with no size, + // can be at the start of an allocation of another type, and a field with no + // size is always traced opaque. So a visit as any other type is a visit to + // the allocation's own type, and its trace covers what is embedded in it. + switch(ponyint_heap_mark_routed(chunk, p, + (t->embed_flags & PONY_EMBED_AT_START) != 0)) + { + case HEAP_MARK_NEW: + recurse(ctx, p, t->trace); + return; + + case HEAP_MARK_SHARED_START_FIRST: + case HEAP_MARK_INTERIOR_FIRST: + // This call set the allocation's shallow mark, so it is the first such + // visit in this mark. A repeat finds the shallow mark set and goes to + // the visit set, keyed by type, so each type at an address is traced at + // most twice in a mark. + recurse(ctx, p, t->trace); + return; + + case HEAP_MARK_MARKED: + case HEAP_MARK_COVERED: + return; + + case HEAP_MARK_SHARED_START: + case HEAP_MARK_INTERIOR: + break; + } + + mark_local_visit(ctx, p, t); +} + +static PONY_FORCEINLINE void send_remote_object(pony_ctx_t* ctx, + pony_actor_t* actor, void* p, pony_type_t* t, int mutability, bool routed) { gc_t* gc = ponyint_actor_gc(ctx->current); actorref_t* aref = ponyint_actormap_getorput(&gc->foreign, actor); @@ -297,7 +543,7 @@ static void send_remote_object(pony_ctx_t* ctx, pony_actor_t* actor, visit_t visit = begin_visit(gc, obj, mutability); - if(visit == VISIT_SKIP) + if(!continue_visit(obj, t, mutability, visit, routed)) return; if(visit == VISIT_FIRST) @@ -330,7 +576,8 @@ static void send_remote_object(pony_ctx_t* ctx, pony_actor_t* actor, } else { obj->rc--; } - } else if((mutability == PONY_TRACE_IMMUTABLE) && !obj->immutable) { + } else if((visit != VISIT_SKIP) && (mutability == PONY_TRACE_IMMUTABLE) && + !obj->immutable) { if(acquire_immutable(ctx, actor, obj, visit)) mutability = PONY_TRACE_MUTABLE; } @@ -338,12 +585,13 @@ static void send_remote_object(pony_ctx_t* ctx, pony_actor_t* actor, if(mutability == PONY_TRACE_OPAQUE) return; - if(mutability == PONY_TRACE_MUTABLE || might_reference_actor(t)) + if(mutability == PONY_TRACE_MUTABLE || traced_by_holders(t)) recurse(ctx, p, t->trace); } -static void recv_remote_object(pony_ctx_t* ctx, pony_actor_t* actor, - void* p, pony_type_t* t, int mutability, chunk_t* chunk) +static PONY_FORCEINLINE void recv_remote_object(pony_ctx_t* ctx, + pony_actor_t* actor, void* p, pony_type_t* t, int mutability, chunk_t* chunk, + bool routed) { gc_t* gc = ponyint_actor_gc(ctx->current); actorref_t* aref = ponyint_actormap_getorput(&gc->foreign, actor); @@ -380,7 +628,7 @@ static void recv_remote_object(pony_ctx_t* ctx, pony_actor_t* actor, visit_t visit = begin_visit(gc, obj, mutability); - if(visit == VISIT_SKIP) + if(!continue_visit(obj, t, mutability, visit, routed)) return; if(visit == VISIT_FIRST) @@ -392,16 +640,16 @@ static void recv_remote_object(pony_ctx_t* ctx, pony_actor_t* actor, { // Increase apparent used memory to provoke GC. ponyint_heap_used(ponyint_actor_heap(ctx->current), - ponyint_heap_size(chunk)); + foreign_size(chunk, t)); - if(mutability == PONY_TRACE_IMMUTABLE && !might_reference_actor(t)) + if(mutability == PONY_TRACE_IMMUTABLE && !traced_by_holders(t)) ponyint_heap_used(ponyint_actor_heap(ctx->current), GC_IMMUT_HEAP_EQUIV); } obj->rc++; - } else if((obj->rc == 1) && (mutability == PONY_TRACE_IMMUTABLE) && - !might_reference_actor(t)) { + } else if((visit != VISIT_SKIP) && (obj->rc == 1) && + (mutability == PONY_TRACE_IMMUTABLE) && !traced_by_holders(t)) { // The earlier tag visit supplied this actor's only reference. Account // for the memory reachable through fields this actor won't trace. ponyint_heap_used(ponyint_actor_heap(ctx->current), GC_IMMUT_HEAP_EQUIV); @@ -413,12 +661,13 @@ static void recv_remote_object(pony_ctx_t* ctx, pony_actor_t* actor, if(mutability == PONY_TRACE_IMMUTABLE) obj->immutable = true; - if(!obj->immutable || might_reference_actor(t)) + if(!obj->immutable || traced_by_holders(t)) recurse(ctx, p, t->trace); } -static void mark_remote_object(pony_ctx_t* ctx, pony_actor_t* actor, - void* p, pony_type_t* t, int mutability, chunk_t* chunk) +static PONY_FORCEINLINE void mark_remote_object(pony_ctx_t* ctx, + pony_actor_t* actor, void* p, pony_type_t* t, int mutability, chunk_t* chunk, + bool routed) { gc_t* gc = ponyint_actor_gc(ctx->current); actorref_t* aref = ponyint_actormap_getorput(&gc->foreign, actor); @@ -440,14 +689,14 @@ static void mark_remote_object(pony_ctx_t* ctx, pony_actor_t* actor, visit_t visit = begin_visit(gc, obj, mutability); - if(visit == VISIT_SKIP) + if(!continue_visit(obj, t, mutability, visit, routed)) return; if(visit == VISIT_FIRST) { // Increase apparent used memory to provoke GC. ponyint_heap_used(ponyint_actor_heap(ctx->current), - ponyint_heap_size(chunk)); + foreign_size(chunk, t)); // Implicitly mark the owner. mark_remote_actor(ctx, gc, aref); @@ -455,11 +704,14 @@ static void mark_remote_object(pony_ctx_t* ctx, pony_actor_t* actor, // Charge for fields traced by the owner even when the first immutable // acquire also requires this actor to trace them. - if(mutability == PONY_TRACE_IMMUTABLE && !might_reference_actor(t)) + if(mutability == PONY_TRACE_IMMUTABLE && !traced_by_holders(t)) ponyint_heap_used(ponyint_actor_heap(ctx->current), GC_IMMUT_HEAP_EQUIV); - if((mutability == PONY_TRACE_IMMUTABLE) && !obj->immutable && (obj->rc > 0)) + if(visit == VISIT_SKIP) { + // Already counted in this epoch. + } else if((mutability == PONY_TRACE_IMMUTABLE) && !obj->immutable && + (obj->rc > 0)) { if(acquire_immutable(ctx, actor, obj, visit)) mutability = PONY_TRACE_MUTABLE; } else if(obj->rc == 0) { @@ -480,48 +732,140 @@ static void mark_remote_object(pony_ctx_t* ctx, pony_actor_t* actor, if(mutability == PONY_TRACE_OPAQUE) return; - if(mutability == PONY_TRACE_MUTABLE || might_reference_actor(t)) + if(mutability == PONY_TRACE_MUTABLE || traced_by_holders(t)) + recurse(ctx, p, t->trace); +} + +// The actor whose allocation holds p, for an object with no heap chunk; NULL +// if t lacks PONY_EMBED_IN_ACTOR or no actor holds p. pagemap_actor is the +// actor the pagemap gave for p, if any. +static pony_actor_t* embedded_field_owner(pony_ctx_t* ctx, void* p, + pony_type_t* t, pony_actor_t* pagemap_actor) +{ + if((t->embed_flags & PONY_EMBED_IN_ACTOR) == 0) + return NULL; + + if(pagemap_actor != NULL) + return pagemap_actor; + + pony_actor_t* current = ctx->current; + + if((current != NULL) && + (((uintptr_t)p - (uintptr_t)current) < current->type->size)) + return current; + + return ponyint_actor_in_pool(p); +} + +// The actor that owns an object with no heap chunk, or NULL for a raw trace +// (pony_trace, with no type), a constant, or memory no actor owns. An unowned +// object isn't collected, so a non-opaque visit to one traces what it +// references here, unless it is in the constant section. pagemap_actor is the +// actor the pagemap gave for p, if any. +static PONY_FORCEINLINE pony_actor_t* chunkless_owner_or_trace(pony_ctx_t* ctx, + void* p, pony_type_t* t, int mutability, pony_actor_t* pagemap_actor) +{ + if((t == NULL) || ponyint_in_const_section(p)) + return NULL; + + pony_actor_t* actor = embedded_field_owner(ctx, p, t, pagemap_actor); + + if((actor == NULL) && (mutability != PONY_TRACE_OPAQUE)) recurse(ctx, p, t->trace); + + return actor; +} + +// Finds the actor that owns an object, and the heap chunk the object is in, if +// any. False when the memory has no heap chunk and chunkless_owner_or_trace +// finds no owner for it, after tracing an unowned object as that function +// does. +static PONY_FORCEINLINE bool object_owner_or_trace(pony_ctx_t* ctx, void* p, + pony_type_t* t, int mutability, pony_actor_t** actor, chunk_t** chunk) +{ + *actor = NULL; + *chunk = ponyint_pagemap_get(p, actor); + + if(*chunk != NULL) + return true; + + *actor = chunkless_owner_or_trace(ctx, p, t, mutability, *actor); + return *actor != NULL; } void ponyint_gc_sendobject(pony_ctx_t* ctx, void* p, pony_type_t* t, int mutability) { - pony_actor_t* actor = NULL; - chunk_t* chunk = ponyint_pagemap_get(p, &actor); + pony_actor_t* actor; + chunk_t* chunk; - // Don't gc memory that wasn't pony_allocated, but do recurse. - if(chunk == NULL) - { - if(mutability != PONY_TRACE_OPAQUE) - recurse(ctx, p, t->trace); + if(!object_owner_or_trace(ctx, p, t, mutability, &actor, &chunk)) return; - } if(actor == ctx->current) - send_local_object(ctx, p, t, mutability); + send_local_object(ctx, p, t, mutability, false); else - send_remote_object(ctx, actor, p, t, mutability); + send_remote_object(ctx, actor, p, t, mutability, false); +} + +void ponyint_gc_sendrouted(pony_ctx_t* ctx, void* p, pony_type_t* t, + int mutability) +{ + pony_actor_t* actor; + chunk_t* chunk; + + if(!object_owner_or_trace(ctx, p, t, mutability, &actor, &chunk)) + return; + + if(actor == ctx->current) + send_local_object(ctx, p, t, mutability, true); + else + send_remote_object(ctx, actor, p, t, mutability, true); } void ponyint_gc_recvobject(pony_ctx_t* ctx, void* p, pony_type_t* t, int mutability) { - pony_actor_t* actor = NULL; - chunk_t* chunk = ponyint_pagemap_get(p, &actor); + pony_actor_t* actor; + chunk_t* chunk; - // Don't gc memory that wasn't pony_allocated, but do recurse. - if(chunk == NULL) - { - if(mutability != PONY_TRACE_OPAQUE) - recurse(ctx, p, t->trace); + if(!object_owner_or_trace(ctx, p, t, mutability, &actor, &chunk)) return; - } if(actor == ctx->current) - recv_local_object(ctx, p, t, mutability); + recv_local_object(ctx, p, t, mutability, false); else - recv_remote_object(ctx, actor, p, t, mutability, chunk); + recv_remote_object(ctx, actor, p, t, mutability, chunk, false); +} + +void ponyint_gc_recvrouted(pony_ctx_t* ctx, void* p, pony_type_t* t, + int mutability) +{ + pony_actor_t* actor; + chunk_t* chunk; + + if(!object_owner_or_trace(ctx, p, t, mutability, &actor, &chunk)) + return; + + if(actor == ctx->current) + recv_local_object(ctx, p, t, mutability, true); + else + recv_remote_object(ctx, actor, p, t, mutability, chunk, true); +} + +// Marks an object in memory with no heap chunk. It is kept out of line so +// that it adds no register pressure to the heap-object path of +// ponyint_gc_markobject, which every mark of a heap object takes. +static PONY_NOINLINE void markobject_chunkless(pony_ctx_t* ctx, void* p, + pony_type_t* t, int mutability, pony_actor_t* pagemap_actor) +{ + pony_actor_t* actor = chunkless_owner_or_trace(ctx, p, t, mutability, + pagemap_actor); + + // Every mark of this actor runs the actor's own trace, which traces its + // embedded fields in place. + if((actor != NULL) && (actor != ctx->current)) + mark_remote_object(ctx, actor, p, t, mutability, NULL, false); } void ponyint_gc_markobject(pony_ctx_t* ctx, void* p, pony_type_t* t, @@ -530,18 +874,35 @@ void ponyint_gc_markobject(pony_ctx_t* ctx, void* p, pony_type_t* t, pony_actor_t* actor = NULL; chunk_t* chunk = ponyint_pagemap_get(p, &actor); - // Don't gc memory that wasn't pony_allocated, but do recurse. + // markobject tests for a missing chunk itself instead of calling + // object_owner_or_trace. mark_local_object needs a chunk, and the test here + // keeps a second NULL-chunk test out of the plain local mark of a heap + // object. if(chunk == NULL) { - if(mutability != PONY_TRACE_OPAQUE) - recurse(ctx, p, t->trace); + markobject_chunkless(ctx, p, t, mutability, actor); return; } if(actor == ctx->current) mark_local_object(ctx, chunk, p, t, mutability); else - mark_remote_object(ctx, actor, p, t, mutability, chunk); + mark_remote_object(ctx, actor, p, t, mutability, chunk, false); +} + +void ponyint_gc_markrouted(pony_ctx_t* ctx, void* p, pony_type_t* t, + int mutability) +{ + pony_actor_t* actor; + chunk_t* chunk; + + if(!object_owner_or_trace(ctx, p, t, mutability, &actor, &chunk)) + return; + + if(actor == ctx->current) + mark_local_object_routed(ctx, chunk, p, t, mutability); + else + mark_remote_object(ctx, actor, p, t, mutability, chunk, true); } void ponyint_gc_sendactor(pony_ctx_t* ctx, pony_actor_t* actor) @@ -599,7 +960,7 @@ object_t* ponyint_gc_next_immutable_root(gc_t* gc, size_t* i) object_t* obj; while((obj = ponyint_objectmap_next(&gc->local, i)) != NULL) { - if(obj->immutable && (obj->rc > 0) && !might_reference_actor(obj->type)) + if(obj->immutable && (obj->rc > 0) && !traced_by_holders(obj->type)) { pony_assert(obj->type != NULL); return obj; @@ -615,6 +976,12 @@ void ponyint_gc_markimmutable(pony_ctx_t* ctx, gc_t* gc) while((obj = ponyint_gc_next_immutable_root(gc, &i)) != NULL) { chunk_t* chunk = ponyint_pagemap_get_chunk(obj->address); + + // An object embedded in this actor has no heap chunk, and every mark of + // the actor runs its own trace, which traces the object in place. + if(chunk == NULL) + continue; + mark_local_object(ctx, chunk, obj->address, obj->type, PONY_TRACE_IMMUTABLE); } diff --git a/src/libponyrt/gc/gc.h b/src/libponyrt/gc/gc.h index 95b24e9f71a..fb1f41ce753 100644 --- a/src/libponyrt/gc/gc.h +++ b/src/libponyrt/gc/gc.h @@ -28,6 +28,29 @@ typedef struct gc_t DECLARE_STACK(ponyint_gcstack, gcstack_t, void); +typedef struct gc_visit_t +{ + void* address; + pony_type_t* type; +} gc_visit_t; + +// An open-addressing set of the (address, type) visits a mark recorded. It +// stores flat pairs with no allocation per entry and is emptied at the end of +// every mark, which the runtime's generic hashmap doesn't fit. +typedef struct gc_visitset_t +{ + gc_visit_t* slots; + size_t count; + size_t capacity; +} gc_visitset_t; + +// Forgets the visits a mark recorded, and releases the storage when the mark +// used little of it. +void ponyint_gc_end_visits(pony_ctx_t* ctx); + +// Releases the storage for recorded visits. +void ponyint_gc_free_visits(pony_ctx_t* ctx); + void ponyint_gc_sendobject(pony_ctx_t* ctx, void* p, pony_type_t* t, int mutability); @@ -37,6 +60,17 @@ void ponyint_gc_recvobject(pony_ctx_t* ctx, void* p, pony_type_t* t, void ponyint_gc_markobject(pony_ctx_t* ctx, void* p, pony_type_t* t, int mutability); +// Send, receive and mark functions for a type that can share an address with an +// object of another type (PONY_EMBED_ROUTED). +void ponyint_gc_sendrouted(pony_ctx_t* ctx, void* p, pony_type_t* t, + int mutability); + +void ponyint_gc_recvrouted(pony_ctx_t* ctx, void* p, pony_type_t* t, + int mutability); + +void ponyint_gc_markrouted(pony_ctx_t* ctx, void* p, pony_type_t* t, + int mutability); + void ponyint_gc_sendactor(pony_ctx_t* ctx, pony_actor_t* actor); void ponyint_gc_recvactor(pony_ctx_t* ctx, pony_actor_t* actor); diff --git a/src/libponyrt/gc/marklocal.c b/src/libponyrt/gc/marklocal.c index cdad4ea56f8..796b963f68f 100644 --- a/src/libponyrt/gc/marklocal.c +++ b/src/libponyrt/gc/marklocal.c @@ -1,5 +1,6 @@ #include "marklocal.h" #include "gc.h" +#include "sections.h" #include "frames.h" #include "../actor/actor.h" #include "../mem/pagemap.h" @@ -114,8 +115,16 @@ static bool queue_object(pony_ctx_t* ctx, void* p, pony_type_t* type, int mode) pony_actor_t* owner = NULL; chunk_t* chunk = ponyint_pagemap_get(p, &owner); - if(owner != ctx->current) + + // Only memory with no heap chunk can be in the constant section, so memory in + // a heap chunk needs no check. + if(chunk == NULL) + { + if(ponyint_in_const_section(p)) + return false; + } else if(owner != ctx->current) { chunk = NULL; + } bool recurse = mode != PONY_TRACE_OPAQUE && type != NULL && type->trace != NULL; @@ -222,6 +231,9 @@ static PONY_NOINLINE pony_ctx_t* begin_mark(pony_ctx_t* scheduler_ctx, mark->ctx.current = actor; mark->ctx.trace_actor = trace_actor; mark->ctx.trace_object = trace_object; + // The local mark records each visit by address and type, so a routed type + // needs no separate function. + mark->ctx.trace_routed = trace_object; if(!ponyint_gc_trace_frames(&mark->ctx, frame)) { @@ -362,7 +374,7 @@ PONY_API bool ponyint_gc_finish(pony_ctx_t* trace_ctx) if(ref->chunk == NULL) continue; if(ref->type != NULL) - ponyint_heap_mark(ref->chunk, ref->address); + ponyint_heap_mark_plain(ref->chunk, ref->address); else ponyint_heap_mark_shallow(ref->chunk, ref->address); } diff --git a/src/libponyrt/gc/objectmap.c b/src/libponyrt/gc/objectmap.c index 807eba9e3b9..3af3f9931a2 100644 --- a/src/libponyrt/gc/objectmap.c +++ b/src/libponyrt/gc/objectmap.c @@ -54,7 +54,7 @@ object_t* ponyint_objectmap_getorput(objectmap_t* map, void* address, if(obj != NULL) { - if(obj->type == NULL) + if((type != NULL) && (obj->type == NULL)) obj->type = type; return obj; } @@ -76,8 +76,10 @@ void ponyint_objectmap_sweep(objectmap_t* map) if(obj->rc > 0) { + // An object in an actor's own allocation has no heap chunk to keep. chunk_t* chunk = ponyint_pagemap_get_chunk(p); - ponyint_heap_mark_shallow(chunk, p); + if(chunk != NULL) + ponyint_heap_mark_shallow(chunk, p); } else { ponyint_objectmap_clearindex(map, i); needs_optimize = true; diff --git a/src/libponyrt/gc/pony_sections.ld b/src/libponyrt/gc/pony_sections.ld new file mode 100644 index 00000000000..003dcb694e3 --- /dev/null +++ b/src/libponyrt/gc/pony_sections.ld @@ -0,0 +1,22 @@ +/* Puts the compiler's type descriptors and then its other constants first in + * .data.rel.ro, which the loader makes read-only after relocation. musl + * applies no RELRO to a static binary, so there both stay writable. + * ponyint_ld_desc_start and ponyint_ld_desc_end mark where the descriptors + * begin and end, and ponyint_ld_const_start and ponyint_ld_const_end where the + * other constants begin and end; gc/sections.c reads them. The section names + * are the ELF names in pony_section_names.h. A program linked without this + * script keeps the descriptors and the other constants in .data.rel.ro and + * leaves the symbols undefined. */ +SECTIONS +{ + .data.rel.ro : { + PROVIDE_HIDDEN(ponyint_ld_desc_start = .); + *(.data.rel.ro.pony-desc) + PROVIDE_HIDDEN(ponyint_ld_desc_end = .); + PROVIDE_HIDDEN(ponyint_ld_const_start = .); + *(.data.rel.ro.pony-const) + PROVIDE_HIDDEN(ponyint_ld_const_end = .); + *(.data.rel.ro.local* .data.rel.ro .data.rel.ro.*) + } +} +INSERT BEFORE .got; diff --git a/src/libponyrt/gc/sections.c b/src/libponyrt/gc/sections.c new file mode 100644 index 00000000000..59a98cf5000 --- /dev/null +++ b/src/libponyrt/gc/sections.c @@ -0,0 +1,111 @@ +#include "sections.h" + +PONY_EXTERN_C_BEGIN + +uintptr_t ponyint_const_section_start; +uintptr_t ponyint_const_section_end; +uintptr_t ponyint_desc_section_start; +uintptr_t ponyint_desc_section_end; + +#if defined(PLATFORM_IS_WINDOWS) + +// One-byte markers around the descriptors and the other constants +// (pony_section_names.h). +#if defined(_MSC_VER) && !defined(__clang__) +# pragma section(PONY_COFF_DESC_START_SECTION, read) +# pragma section(PONY_COFF_CONST_START_SECTION, read) +# pragma section(PONY_COFF_CONST_END_SECTION, read) +# define SECTION_MARKER(name) __declspec(allocate(name)) +#else +# define SECTION_MARKER(name) __attribute__((section(name), used)) +#endif + +SECTION_MARKER(PONY_COFF_DESC_START_SECTION) + const char ponyint_desc_marker_start[1] = {0}; +SECTION_MARKER(PONY_COFF_CONST_START_SECTION) + const char ponyint_const_marker_start[1] = {0}; +SECTION_MARKER(PONY_COFF_CONST_END_SECTION) + const char ponyint_const_marker_end[1] = {0}; + +void ponyint_section_bounds_init(void) +{ + ponyint_desc_section_start = (uintptr_t)ponyint_desc_marker_start; + ponyint_desc_section_end = (uintptr_t)ponyint_const_marker_start; + ponyint_const_section_start = (uintptr_t)ponyint_const_marker_start; + ponyint_const_section_end = (uintptr_t)ponyint_const_marker_end; +} + +#elif defined(PLATFORM_IS_MACOSX) + +// The linker defines these for each section. The runtime puts a one-byte marker +// in each section, so both sections exist in every program that links the +// runtime. +#define MACHO_BOUND(edge, section) \ + __asm("section$" edge "$" PONY_MACHO_SEGMENT "$" section) + +extern const char ponyint_const_macho_start[] + MACHO_BOUND("start", PONY_MACHO_CONST_SECTION); +extern const char ponyint_const_macho_end[] + MACHO_BOUND("end", PONY_MACHO_CONST_SECTION); +extern const char ponyint_desc_macho_start[] + MACHO_BOUND("start", PONY_MACHO_DESC_SECTION); +extern const char ponyint_desc_macho_end[] + MACHO_BOUND("end", PONY_MACHO_DESC_SECTION); + +PONY_CONSTANT_SECTION static const char const_section_marker = 0; +PONY_DESCRIPTOR_SECTION static const char desc_section_marker = 0; + +void ponyint_section_bounds_init(void) +{ + ponyint_const_section_start = (uintptr_t)ponyint_const_macho_start; + ponyint_const_section_end = (uintptr_t)ponyint_const_macho_end; + ponyint_desc_section_start = (uintptr_t)ponyint_desc_macho_start; + ponyint_desc_section_end = (uintptr_t)ponyint_desc_macho_end; +} + +#elif defined(__ELF__) + +// A writable byte in .data.rel.ro. If every input to that section is read-only, +// as in code built without PIC, lld gives the program two RELRO regions and +// glibc protects only one of them. One writable input keeps a single region. +__attribute__((section(".data.rel.ro"), used)) +static char relro_anchor = 0; + +// Defined by the linker script ponyc passes (pony_sections.ld). A program +// linked without it leaves them undefined, and nothing counts as a constant or +// a descriptor. +extern const char ponyint_ld_desc_start[] + __attribute__((weak, visibility("hidden"))); +extern const char ponyint_ld_desc_end[] + __attribute__((weak, visibility("hidden"))); +extern const char ponyint_ld_const_start[] + __attribute__((weak, visibility("hidden"))); +extern const char ponyint_ld_const_end[] + __attribute__((weak, visibility("hidden"))); + +void ponyint_section_bounds_init(void) +{ + uintptr_t desc_start = (uintptr_t)ponyint_ld_desc_start; + uintptr_t desc_end = (uintptr_t)ponyint_ld_desc_end; + uintptr_t const_start = (uintptr_t)ponyint_ld_const_start; + uintptr_t const_end = (uintptr_t)ponyint_ld_const_end; + + if((desc_start == 0) || (desc_end < desc_start) || + (const_start < desc_end) || (const_end < const_start)) + return; + + ponyint_desc_section_start = desc_start; + ponyint_desc_section_end = desc_end; + ponyint_const_section_start = const_start; + ponyint_const_section_end = const_end; +} + +#else + +void ponyint_section_bounds_init(void) +{ +} + +#endif + +PONY_EXTERN_C_END diff --git a/src/libponyrt/gc/sections.h b/src/libponyrt/gc/sections.h new file mode 100644 index 00000000000..a0c0a719170 --- /dev/null +++ b/src/libponyrt/gc/sections.h @@ -0,0 +1,93 @@ +#ifndef gc_sections_h +#define gc_sections_h + +#include +#include +#include "../pony.h" +#include +#include + +PONY_EXTERN_C_BEGIN + +// The bounds of the section that holds the objects the compiler emits as +// constants: string literals, constant array literals and primitive instances. +// Both are 0 until ponyint_section_bounds_init runs, and stay 0 in an ELF +// program linked without ponyc's linker script and on a target with no constant +// section, where no address counts as a constant. +extern uintptr_t ponyint_const_section_start; +extern uintptr_t ponyint_const_section_end; + +// The bounds of the section that holds the compiler's type descriptors, set +// with the bounds above. +extern uintptr_t ponyint_desc_section_start; +extern uintptr_t ponyint_desc_section_end; + +// Finds both sections. Call it before any scheduler thread starts and before +// any actor is created. The bounds must not change while actors exist: whether +// an actor has a pagemap entry is decided from them when it is created and +// again when it is destroyed. +void ponyint_section_bounds_init(void); + +// Places a C object in the constant section, as the compiler places its +// constants. +#if defined(PLATFORM_IS_WINDOWS) +# if defined(_MSC_VER) && !defined(__clang__) +# pragma section(PONY_COFF_CONST_SECTION, read) +# define PONY_CONSTANT_SECTION __declspec(allocate(PONY_COFF_CONST_SECTION)) +# else +# define PONY_CONSTANT_SECTION \ + __attribute__((section(PONY_COFF_CONST_SECTION), used)) +# endif +#elif defined(PLATFORM_IS_MACOSX) +# define PONY_CONSTANT_SECTION __attribute__((section( \ + PONY_MACHO_SEGMENT "," PONY_MACHO_CONST_SECTION), used)) +#elif defined(__ELF__) +# define PONY_CONSTANT_SECTION \ + __attribute__((section(PONY_ELF_CONST_SECTION), used)) +#else +# define PONY_CONSTANT_SECTION +#endif + +// Places a C type descriptor in the descriptor section, as the compiler places +// its descriptors. +#if defined(PLATFORM_IS_WINDOWS) +# if defined(_MSC_VER) && !defined(__clang__) +# pragma section(PONY_COFF_DESC_SECTION, read) +# define PONY_DESCRIPTOR_SECTION __declspec(allocate(PONY_COFF_DESC_SECTION)) +# else +# define PONY_DESCRIPTOR_SECTION \ + __attribute__((section(PONY_COFF_DESC_SECTION), used)) +# endif +#elif defined(PLATFORM_IS_MACOSX) +# define PONY_DESCRIPTOR_SECTION __attribute__((section( \ + PONY_MACHO_SEGMENT "," PONY_MACHO_DESC_SECTION), used)) +#elif defined(__ELF__) +# define PONY_DESCRIPTOR_SECTION \ + __attribute__((section(PONY_ELF_DESC_SECTION), used)) +#else +# define PONY_DESCRIPTOR_SECTION +#endif + +// Whether p is in the compiler's constant section. Nothing writes an object +// there at run time, so the GC traces neither the object nor what it points +// to. +static inline bool ponyint_in_const_section(const void* p) +{ + return ((uintptr_t)p - ponyint_const_section_start) < + (ponyint_const_section_end - ponyint_const_section_start); +} + +// Whether all of a type descriptor is in the descriptor section, so every field +// of it can be read. Only type descriptors and the runtime's one-byte markers +// are there, so a pointer to any other constant fails this. +static inline bool ponyint_desc_section_holds(const pony_type_t* type) +{ + uintptr_t size = ponyint_desc_section_end - ponyint_desc_section_start; + + return (((uintptr_t)type - ponyint_desc_section_start) < size) && + (((uintptr_t)type + sizeof(*type) - 1 - ponyint_desc_section_start) < size); +} + +PONY_EXTERN_C_END + +#endif diff --git a/src/libponyrt/gc/trace.c b/src/libponyrt/gc/trace.c index 48ec9855617..e6ab0a3a078 100644 --- a/src/libponyrt/gc/trace.c +++ b/src/libponyrt/gc/trace.c @@ -1,16 +1,20 @@ #include "trace.h" #include "gc.h" +#include "embedflags.h" #include "../sched/scheduler.h" #include "../sched/cpu.h" #include "../actor/actor.h" #include "../tracing/tracing.h" #include "ponyassert.h" +PONY_EXTERN_C_BEGIN + PONY_API void pony_gc_send(pony_ctx_t* ctx, pony_actor_t* to) { pony_assert(ctx->current != NULL); pony_assert(ctx->stack == NULL); ctx->trace_object = ponyint_gc_sendobject; + ctx->trace_routed = ponyint_gc_sendrouted; ctx->trace_actor = ponyint_gc_sendactor; // Record the destination of the message being traced so the send-trace can @@ -28,6 +32,7 @@ PONY_API void pony_gc_recv(pony_ctx_t* ctx) pony_assert(ctx->current != NULL); pony_assert(ctx->stack == NULL); ctx->trace_object = ponyint_gc_recvobject; + ctx->trace_routed = ponyint_gc_recvrouted; ctx->trace_actor = ponyint_gc_recvactor; } @@ -35,6 +40,7 @@ void ponyint_gc_mark(pony_ctx_t* ctx) { pony_assert(ctx->stack == NULL); ctx->trace_object = ponyint_gc_markobject; + ctx->trace_routed = ponyint_gc_markrouted; ctx->trace_actor = ponyint_gc_markactor; } @@ -50,6 +56,7 @@ PONY_API void pony_send_done(pony_ctx_t* ctx) // ASIO and bootstrap paths pass NULL), so nothing reads a stale value. ctx->msg_target = NULL; ctx->trace_object = NULL; + ctx->trace_routed = NULL; } PONY_API void pony_recv_done(pony_ctx_t* ctx) @@ -58,12 +65,14 @@ PONY_API void pony_recv_done(pony_ctx_t* ctx) ponyint_gc_handlestack(ctx); ponyint_gc_done(ponyint_actor_gc(ctx->current)); ctx->trace_object = NULL; + ctx->trace_routed = NULL; } void ponyint_mark_done(pony_ctx_t* ctx) { ponyint_gc_markimmutable(ctx, ponyint_actor_gc(ctx->current)); ponyint_gc_handlestack(ctx); + ponyint_gc_end_visits(ctx); #ifdef USE_RUNTIMESTATS uint64_t used_cpu = ponyint_sched_cpu_used(ctx); @@ -77,6 +86,7 @@ void ponyint_mark_done(pony_ctx_t* ctx) ponyint_gc_sweep(ctx, ponyint_actor_gc(ctx->current)); ponyint_gc_done(ponyint_actor_gc(ctx->current)); ctx->trace_object = NULL; + ctx->trace_routed = NULL; } PONY_API void pony_send_next(pony_ctx_t* ctx, pony_actor_t* to) @@ -93,23 +103,59 @@ PONY_API void pony_send_next(pony_ctx_t* ctx, pony_actor_t* to) ponyint_gc_done(ponyint_actor_gc(ctx->current)); } +// Tagged pointers have bit 63 set. They encode a machine word directly in the +// pointer and have no heap allocation to trace. +static bool tagged_pointer(void* p) +{ + return (sizeof(uintptr_t) >= 8) && (((uintptr_t)p >> 63) != 0); +} + PONY_API void pony_trace(pony_ctx_t* ctx, void* p) { - // Tagged pointers have bit 63 set. They encode a machine word directly - // in the pointer and have no heap allocation to trace. - if((sizeof(uintptr_t) >= 8) && (((uintptr_t)p >> 63) != 0)) + // An empty Array holds a null pointer, which points at no memory. + if((p == NULL) || tagged_pointer(p)) return; ctx->trace_object(ctx, p, NULL, PONY_TRACE_OPAQUE); } +PONY_API void pony_traceknown_routed(pony_ctx_t* ctx, void* p, + pony_type_t* t, int m) +{ + if(tagged_pointer(p)) + return; + + // C code can't know whether a type is routed, so this takes any type. + if(t->dispatch != NULL) + { + ctx->trace_actor(ctx, (pony_actor_t*)p); + return; + } + + if((t->embed_flags & PONY_EMBED_ROUTED) == 0) + { + ctx->trace_object(ctx, p, t, m); + return; + } + + // An object with no size can share its address with another object, so it + // is traced as opaque; a non-opaque visit would mark that address as traced. + if(t->size == 0) + m = PONY_TRACE_OPAQUE; + + pony_assert(ctx->trace_routed != NULL); + ctx->trace_routed(ctx, p, t, m); +} + PONY_API void pony_traceknown(pony_ctx_t* ctx, void* p, pony_type_t* t, int m) { - // Tagged pointers have bit 63 set. They encode a machine word directly - // in the pointer and have no heap allocation to trace. - if((sizeof(uintptr_t) >= 8) && (((uintptr_t)p >> 63) != 0)) + if(tagged_pointer(p)) return; + // A type with PONY_EMBED_ROUTED is traced with pony_traceknown_routed + // (pony.h). + pony_assert((t->embed_flags & PONY_EMBED_ROUTED) == 0); + if(t->dispatch != NULL) { ctx->trace_actor(ctx, (pony_actor_t*)p); @@ -120,17 +166,42 @@ PONY_API void pony_traceknown(pony_ctx_t* ctx, void* p, pony_type_t* t, int m) PONY_API void pony_traceunknown(pony_ctx_t* ctx, void* p, int m) { - // Tagged pointers have bit 63 set. They encode a machine word directly - // in the pointer and have no heap allocation to trace. - if((sizeof(uintptr_t) >= 8) && (((uintptr_t)p >> 63) != 0)) + if(tagged_pointer(p)) + return; + + pony_type_t* t = *(pony_type_t**)p; + + // A trace that can reach a type with PONY_EMBED_ROUTED calls + // pony_traceunknown_routed instead (pony.h). + pony_assert((t->embed_flags & PONY_EMBED_ROUTED) == 0); + + if(t->dispatch != NULL) + { + ctx->trace_actor(ctx, (pony_actor_t*)p); + } else { + ctx->trace_object(ctx, p, t, m); + } +} + +PONY_API void pony_traceunknown_routed(pony_ctx_t* ctx, void* p, int m) +{ + if(tagged_pointer(p)) return; + // A struct object doesn't start with a descriptor pointer, so it is never + // traced here, and only a struct can be a routed type with no size: unlike + // pony_traceknown_routed, this needs no opaque rule. pony_type_t* t = *(pony_type_t**)p; if(t->dispatch != NULL) { ctx->trace_actor(ctx, (pony_actor_t*)p); + } else if((t->embed_flags & PONY_EMBED_ROUTED) != 0) { + pony_assert(ctx->trace_routed != NULL); + ctx->trace_routed(ctx, p, t, m); } else { ctx->trace_object(ctx, p, t, m); } } + +PONY_EXTERN_C_END diff --git a/src/libponyrt/mem/heap.c b/src/libponyrt/mem/heap.c index c9368bcddc2..3fa6f506e9e 100644 --- a/src/libponyrt/mem/heap.c +++ b/src/libponyrt/mem/heap.c @@ -16,6 +16,7 @@ typedef struct chunk_t // used for pointer tagging // bit 0 (lowest bit) for keeping track of chunk type (1 = small; 0 = large) // bit 1 for keeping track of chunks to be cleared + // higher bits: see the SMALL_CHUNK_* and LARGE_CHUNK_* bitmasks below char* m; union { @@ -26,6 +27,9 @@ typedef struct chunk_t uint32_t slots; uint32_t shallow; uint32_t finalisers; + // For a slot with a finaliser, a set bit means its object is fully + // constructed. For a slot without one, a set bit means its allocation's + // start is shared (see ponyint_heap_alloc_small_shared_start). uint32_t traceable; } small; struct @@ -53,7 +57,10 @@ typedef struct chunk_t #define LARGE_CHUNK_SHALLOW_BITMASK ((uintptr_t)0x1 << LARGE_CHUNK_SHALLOW_BITMASK_SHIFT_AMOUNT) #define LARGE_CHUNK_FINALISER_BITMASK_SHIFT_AMOUNT (uintptr_t)4 #define LARGE_CHUNK_FINALISER_BITMASK ((uintptr_t)0x1 << LARGE_CHUNK_FINALISER_BITMASK_SHIFT_AMOUNT) -#define CHUNK_M_BITMASK ~(CHUNK_TYPE_BITMASK | CHUNK_NEEDS_TO_BE_CLEARED_BITMASK | SMALL_CHUNK_SIZECLASS_BITMASK | LARGE_CHUNK_SLOT_BITMASK | LARGE_CHUNK_SHALLOW_BITMASK | LARGE_CHUNK_FINALISER_BITMASK) +// A bit of m rather than large.traceable, which sweep_large overwrites. +#define LARGE_CHUNK_SHARED_START_BITMASK_SHIFT_AMOUNT (uintptr_t)5 +#define LARGE_CHUNK_SHARED_START_BITMASK ((uintptr_t)0x1 << LARGE_CHUNK_SHARED_START_BITMASK_SHIFT_AMOUNT) +#define CHUNK_M_BITMASK ~(CHUNK_TYPE_BITMASK | CHUNK_NEEDS_TO_BE_CLEARED_BITMASK | SMALL_CHUNK_SIZECLASS_BITMASK | LARGE_CHUNK_SLOT_BITMASK | LARGE_CHUNK_SHALLOW_BITMASK | LARGE_CHUNK_FINALISER_BITMASK | LARGE_CHUNK_SHARED_START_BITMASK) enum { @@ -248,6 +255,32 @@ static void set_large_chunk_finaliser(chunk_t* chunk, uint32_t finaliser) chunk->m = (char*)(((uintptr_t)chunk->m & ~LARGE_CHUNK_FINALISER_BITMASK) | finaliser); } +static bool get_small_slot_shared_start(chunk_t* chunk, uint32_t slot) +{ + return (chunk->small.traceable & ~chunk->small.finalisers & slot) != 0; +} + +static void set_small_slot_shared_start(chunk_t* chunk, uint32_t slot) +{ + pony_assert((chunk->small.finalisers & slot) == 0); + chunk->small.traceable |= slot; +} + +static uint32_t get_large_chunk_shared_start(chunk_t* chunk) +{ + pony_assert(!get_chunk_is_small_chunk(chunk)); + return ((uintptr_t)chunk->m & LARGE_CHUNK_SHARED_START_BITMASK) != 0; +} + +static void set_large_chunk_shared_start(chunk_t* chunk, uint32_t shared) +{ + pony_assert(!get_chunk_is_small_chunk(chunk)); + uintptr_t bit = + (uintptr_t)(!!shared) << LARGE_CHUNK_SHARED_START_BITMASK_SHIFT_AMOUNT; + chunk->m = (char*) + (((uintptr_t)chunk->m & ~LARGE_CHUNK_SHARED_START_BITMASK) | bit); +} + static size_t get_small_chunk_size(chunk_t* chunk) { pony_assert(get_chunk_is_small_chunk(chunk)); @@ -511,9 +544,12 @@ static size_t sweep_small(chunk_t* chunk, chunk_t** avail, chunk_t** full, chunk // A deep mark comes from a readable reference to the object itself, // which can't exist until every field is defined, or from keeping a - // finaliser that was already traceable. - chunk->small.traceable = chunk->small.finalisers & ~chunk->small.slots; + // finaliser that was already traceable. A shared start lasts while the + // slot is in use. + uint32_t shared = chunk->small.traceable & ~chunk->small.finalisers; + uint32_t traceable = chunk->small.finalisers & ~chunk->small.slots; chunk->small.slots &= chunk->small.shallow; + chunk->small.traceable = traceable | (shared & ~chunk->small.slots); set_chunk_needs_clearing(chunk); @@ -739,8 +775,14 @@ void* ponyint_heap_alloc(pony_actor_t* actor, heap_t* heap, size_t size, } } -void* ponyint_heap_alloc_small(pony_actor_t* actor, heap_t* heap, - uint32_t sizeclass, uint32_t track_finalisers_mask) +// shared_start records the allocation as a struct that starts with an +// embedded field with a non-zero size (see ponyint_heap_mark_routed). +// heap_alloc_small and heap_alloc_large are inlined into each caller, so a +// caller that passes a constant flag gets a version without the checks that +// the constant rules out. +static PONY_FORCEINLINE void* heap_alloc_small(pony_actor_t* actor, + heap_t* heap, uint32_t sizeclass, uint32_t track_finalisers_mask, + bool shared_start) { // 1. when `track_finalisers_mask == TRACK_NO_FINALISERS` then finalisers are // disabled @@ -841,12 +883,28 @@ void* ponyint_heap_alloc_small(pony_actor_t* actor, heap_t* heap, ASAN_UNPOISON_MEMORY_REGION(m, SIZECLASS_SIZE(sizeclass)); #endif + // A struct has no finaliser, so the slot's traceable bit is free. + if(shared_start) + set_small_slot_shared_start(chunk, FIND_SLOT(m, get_m(chunk))); + heap->used += SIZECLASS_SIZE(sizeclass); return m; } -void* ponyint_heap_alloc_large(pony_actor_t* actor, heap_t* heap, size_t size, - uint32_t track_finalisers_mask) +void* ponyint_heap_alloc_small(pony_actor_t* actor, heap_t* heap, + uint32_t sizeclass, uint32_t track_finalisers_mask) +{ + return heap_alloc_small(actor, heap, sizeclass, track_finalisers_mask, false); +} + +void* ponyint_heap_alloc_small_shared_start(pony_actor_t* actor, heap_t* heap, + uint32_t sizeclass) +{ + return heap_alloc_small(actor, heap, sizeclass, TRACK_NO_FINALISERS, true); +} + +static PONY_FORCEINLINE void* heap_alloc_large(pony_actor_t* actor, + heap_t* heap, size_t size, uint32_t track_finalisers_mask, bool shared_start) { // 1. when `track_finalisers_mask == TRACK_NO_FINALISERS` then finalisers are // disabled @@ -939,6 +997,7 @@ void* ponyint_heap_alloc_large(pony_actor_t* actor, heap_t* heap, size_t size, // note if a finaliser needs to run or not set_large_chunk_finaliser(chunk, (track_finalisers_mask & 1)); + set_large_chunk_shared_start(chunk, shared_start ? 1 : 0); chunk->large.traceable = false; chunk->large.local_index = 0; @@ -953,6 +1012,18 @@ void* ponyint_heap_alloc_large(pony_actor_t* actor, heap_t* heap, size_t size, return get_m(chunk); } +void* ponyint_heap_alloc_large(pony_actor_t* actor, heap_t* heap, size_t size, + uint32_t track_finalisers_mask) +{ + return heap_alloc_large(actor, heap, size, track_finalisers_mask, false); +} + +void* ponyint_heap_alloc_large_shared_start(pony_actor_t* actor, heap_t* heap, + size_t size) +{ + return heap_alloc_large(actor, heap, size, TRACK_NO_FINALISERS, true); +} + void* ponyint_heap_realloc(pony_actor_t* actor, heap_t* heap, void* p, size_t size, size_t copy) { @@ -1050,41 +1121,90 @@ void ponyint_heap_mark_slots(chunk_t* chunk, uint32_t slots, bool shallow) } } -bool ponyint_heap_mark(chunk_t* chunk, void* p) +// may_be_start_field is whether the object visited at p may be the field +// embedded at the start of a struct, rather than the allocation's own type. +// Inlined into each caller, so a caller that passes a constant gets a version +// without the checks that the constant rules out. +static PONY_FORCEINLINE heap_mark_t heap_mark_visit(chunk_t* chunk, void* p, + bool may_be_start_field) { - // If it's an internal pointer, we shallow mark it instead. This will - // preserve the external pointer, but allow us to mark and recurse the - // external pointer in the same pass. - bool marked; - maybe_clear_chunk(chunk); if(get_chunk_is_small_chunk(chunk)) { - // Calculate the external pointer. void* ext = EXTERNAL_PTR(p, get_small_chunk_size(chunk)); - - // Shift to account for smallest allocation size. uint32_t slot = FIND_SLOT(ext, get_m(chunk)); - // Check if it was already marked. - marked = (chunk->small.slots & slot) == 0; - // A clear bit is in-use, a set bit is available. - if(p == ext) - chunk->small.slots &= ~slot; - else + bool marked = (chunk->small.slots & slot) == 0; + + if(p != ext) + { + if(marked) + return HEAP_MARK_COVERED; + + bool first = (chunk->small.shallow & slot) != 0; chunk->small.shallow &= ~slot; - } else { - marked = get_large_chunk_slot(chunk) == 0; + return first ? HEAP_MARK_INTERIOR_FIRST : HEAP_MARK_INTERIOR; + } - if(p == get_m(chunk)) - set_large_chunk_slot(chunk, 0); - else - set_large_chunk_shallow(chunk, 0); + if(marked) + return HEAP_MARK_MARKED; + + if(may_be_start_field && get_small_slot_shared_start(chunk, slot)) + { + bool first = (chunk->small.shallow & slot) != 0; + chunk->small.shallow &= ~slot; + return first ? HEAP_MARK_SHARED_START_FIRST : HEAP_MARK_SHARED_START; + } + + chunk->small.slots &= ~slot; + return HEAP_MARK_NEW; + } + + bool marked = get_large_chunk_slot(chunk) == 0; + + if(p != get_m(chunk)) + { + if(marked) + return HEAP_MARK_COVERED; + + bool first = get_large_chunk_shallow(chunk) != 0; + set_large_chunk_shallow(chunk, 0); + return first ? HEAP_MARK_INTERIOR_FIRST : HEAP_MARK_INTERIOR; + } + + if(marked) + return HEAP_MARK_MARKED; + + if(may_be_start_field && get_large_chunk_shared_start(chunk)) + { + bool first = get_large_chunk_shallow(chunk) != 0; + set_large_chunk_shallow(chunk, 0); + return first ? HEAP_MARK_SHARED_START_FIRST : HEAP_MARK_SHARED_START; } - return marked; + set_large_chunk_slot(chunk, 0); + return HEAP_MARK_NEW; +} + +// When the runtime's bitcode is linked into a program and optimised with it, +// these can be inlined into the GC's mark path, where they run once per visit. +#if defined(__clang__) +__attribute__((always_inline)) +#endif +heap_mark_t ponyint_heap_mark_routed(chunk_t* chunk, void* p, + bool may_be_start_field) +{ + return heap_mark_visit(chunk, p, may_be_start_field); +} + +#if defined(__clang__) +__attribute__((always_inline)) +#endif +heap_mark_t ponyint_heap_mark_plain(chunk_t* chunk, void* p) +{ + return heap_mark_visit(chunk, p, false); } void ponyint_heap_mark_shallow(chunk_t* chunk, void* p) @@ -1138,10 +1258,10 @@ void ponyint_heap_free(chunk_t* chunk, void* p) // clear finaliser chunk->small.finalisers &= ~slot; - chunk->small.traceable &= ~slot; } // free slot + chunk->small.traceable &= ~slot; chunk->small.slots |= slot; } } diff --git a/src/libponyrt/mem/heap.h b/src/libponyrt/mem/heap.h index 2239e1e3193..1c467f074b2 100644 --- a/src/libponyrt/mem/heap.h +++ b/src/libponyrt/mem/heap.h @@ -78,6 +78,23 @@ void* ponyint_heap_alloc_large(pony_actor_t* actor, heap_t* heap, size_t size, uint32_t track_finalisers_mask) ); +/** + * Allocate a struct that starts with an embedded field with a non-zero size, + * and record that its start is shared, so an object traced at that address may + * be only that field. ponyint_heap_mark_routed marks such an allocation only + * for a visit of its own type. The struct must not have a finaliser. + */ +__pony_spec_malloc__( +void* ponyint_heap_alloc_small_shared_start(pony_actor_t* actor, heap_t* heap, + uint32_t sizeclass) + ); + +/// As ponyint_heap_alloc_small_shared_start, for a struct larger than HEAP_MAX. +__pony_spec_malloc__( +void* ponyint_heap_alloc_large_shared_start(pony_actor_t* actor, heap_t* heap, + size_t size) + ); + void* ponyint_heap_realloc(pony_actor_t* actor, heap_t* heap, void* p, size_t size, size_t copy); @@ -94,19 +111,62 @@ void ponyint_heap_startgc(heap_t* heap ); #endif +typedef enum +{ + // p starts its allocation, which this call marked. + HEAP_MARK_NEW, + // p starts its allocation, which was already marked. + HEAP_MARK_MARKED, + // p starts an unmarked allocation whose start is shared, and the object + // traced there may be only the field at the start. The allocation's shallow + // mark, which keeps it, was already set. + HEAP_MARK_SHARED_START, + // p starts an unmarked allocation whose start is shared, and the object + // traced there may be only the field at the start. This call set the + // allocation's shallow mark, which keeps it. + HEAP_MARK_SHARED_START_FIRST, + // p is inside an unmarked allocation whose shallow mark, which keeps it, was + // already set, by an earlier visit or an opaque one. + HEAP_MARK_INTERIOR, + // p is inside an unmarked allocation, and this call set the allocation's + // shallow mark, which keeps it. + HEAP_MARK_INTERIOR_FIRST, + // p is inside its allocation, which is already marked. + HEAP_MARK_COVERED +} heap_mark_t; + +/** + * Mark the allocation that p is in, if p starts it, and report what was found, + * for an object whose type can share an address with an object of another + * type. A pointer inside the allocation keeps it with a shallow mark. + * may_be_start_field is true when the object traced at p may be the field + * embedded at the start of a struct; at a shared start, the allocation then + * isn't marked. False means the object at p is of the allocation's own type, so + * a visit to the allocation's start marks it. + */ +heap_mark_t ponyint_heap_mark_routed(chunk_t* chunk, void* p, + bool may_be_start_field); + /** - * Mark an address in a chunk. Returns true if it was already marked, or false - * if you have just marked it. + * The same as ponyint_heap_mark_routed with may_be_start_field false. It treats + * the object at p as of the allocation's own type, so a visit to the start + * marks the allocation, whether or not its start is shared. Never returns + * HEAP_MARK_SHARED_START or HEAP_MARK_SHARED_START_FIRST. */ -bool ponyint_heap_mark(chunk_t* chunk, void* p); +heap_mark_t ponyint_heap_mark_plain(chunk_t* chunk, void* p); uint32_t ponyint_heap_base_slot(chunk_t* chunk, void* p); uint32_t* ponyint_heap_local_index(chunk_t* chunk); void ponyint_heap_mark_slots(chunk_t* chunk, uint32_t slots, bool shallow); /** - * Marks an address, but does not affect the return value of ponyint_heap_mark() - * for the same address, nor does it indicate previous mark status. + * Sets the shallow mark of the allocation that holds p, without marking the + * allocation. For the rest of the current mark: a visit to the allocation's + * start, before the allocation is marked, marks it and returns HEAP_MARK_NEW, + * except ponyint_heap_mark_routed() with may_be_start_field true at a shared + * start, which returns HEAP_MARK_SHARED_START and leaves it unmarked; a visit + * inside the allocation, before it is marked, returns HEAP_MARK_INTERIOR; and + * no visit returns a _FIRST result. */ void ponyint_heap_mark_shallow(chunk_t* chunk, void* p); diff --git a/src/libponyrt/mem/pagemap.c b/src/libponyrt/mem/pagemap.c index 44e0cad2fd0..c4eab76b9a9 100644 --- a/src/libponyrt/mem/pagemap.c +++ b/src/libponyrt/mem/pagemap.c @@ -121,11 +121,9 @@ chunk_t* ponyint_pagemap_get_chunk(const void* addr) * times in order to retrieve both the chunk_t* and the pony_actor_t*. * * NOTE: the multiple atomic instructions to retrieve the chunk_t* followed - * by the pony_actor_t* should be safe because the only time the pagemap - * is updated is when a chunk_t is first allocated by an actor or when the - * chunk_t is deallocated/freed by GC and in both scenarios the only actor - * with a reference to memory that would resolve to that pagemap entry is - * the owning actor of the chunk_t. + * by the pony_actor_t* should be safe because every update to the pagemap + * happens while at most one actor can hold a reference to memory that would + * resolve to that pagemap entry. */ chunk_t* ponyint_pagemap_get(const void* addr, pony_actor_t** actor) { @@ -168,11 +166,9 @@ chunk_t* ponyint_pagemap_get(const void* addr, pony_actor_t** actor) * a small chunk_t (exactly one pagemap entry). * * NOTE: the multiple atomic instructions to set the chunk_t* followed - * by the pony_actor_t* should be safe because the only time the pagemap - * is updated is when a chunk_t is first allocated by an actor or when the - * chunk_t is deallocated/freed by GC and in both scenarios the only actor - * with a reference to memory that would resolve to that pagemap entry is - * the owning actor of the chunk_t. + * by the pony_actor_t* should be safe because every update to the pagemap + * happens while at most one actor can hold a reference to memory that would + * resolve to that pagemap entry. */ void ponyint_pagemap_set(const void* addr, chunk_t* chunk, pony_actor_t* actor) { @@ -244,11 +240,9 @@ void ponyint_pagemap_set(const void* addr, chunk_t* chunk, pony_actor_t* actor) * a large chunk_t's (more than one pagemap entry required). * * NOTE: the multiple atomic instructions to set the chunk_t* followed - * by the pony_actor_t* should be safe because the only time the pagemap - * is updated is when a chunk_t is first allocated by an actor or when the - * chunk_t is deallocated/freed by GC and in both scenarios the only actor - * with a reference to memory that would resolve to that pagemap entry is - * the owning actor of the chunk_t. + * by the pony_actor_t* should be safe because every update to the pagemap + * happens while at most one actor can hold a reference to memory that would + * resolve to that pagemap entry. */ void ponyint_pagemap_set_bulk(const void* addr, chunk_t* chunk, pony_actor_t* actor, size_t size) { diff --git a/src/libponyrt/mem/pool.h b/src/libponyrt/mem/pool.h index bf1acd4e1cc..55a79623163 100644 --- a/src/libponyrt/mem/pool.h +++ b/src/libponyrt/mem/pool.h @@ -80,6 +80,21 @@ void ponyint_pool_thread_cleanup(); */ void ponyint_pool_suspend_flush(); +/* The start of the pool allocation that contains p, or NULL if p is not in + * an allocation from an arena: memory from elsewhere, an allocation too large + * for an arena, or an arena unit that holds no allocation. p must point into a + * live allocation or outside the pool. With a pointer into freed pool memory + * the call can give any answer, or fault where a released arena's memory is + * decommitted. The memalign backend has no arenas and always returns NULL. + */ +void* ponyint_pool_base(void* p); + +/* Whether ponyint_pool_alloc_size puts an allocation of this size in an arena, + * so that ponyint_pool_base finds its start. Always false for the memalign + * backend. + */ +bool ponyint_pool_size_in_arena(size_t size); + void ponyint_pool_drain(); /* return_idle gives up this thread's held-but-free memory: the arena backend diff --git a/src/libponyrt/mem/pool_arena.c b/src/libponyrt/mem/pool_arena.c index 755e69685b6..cf6b7e78b60 100644 --- a/src/libponyrt/mem/pool_arena.c +++ b/src/libponyrt/mem/pool_arena.c @@ -295,6 +295,74 @@ pony_static_assert(REGION_ARENAS == 32, static PONY_ATOMIC(region_t*) regions_head; +/// One bit per REGION_SIZE of address space below REGION_MAP_LIMIT, set for +/// each region when it is created and never cleared: regions are never +/// unmapped, so an address's region can be found without walking the region +/// list. A region at or above the limit is found by the walk. Only the pages +/// holding set bits are ever written. +#ifdef PLATFORM_IS_ILP32 +# define REGION_MAP_LIMIT ((uint64_t)1 << 32) +pony_static_assert(sizeof(uintptr_t) == 4, + "an ILP32 region map covers only 32-bit addresses"); +#else +# define REGION_MAP_LIMIT ((uint64_t)1 << 48) +#endif +#define REGION_MAP_WORD_BITS (sizeof(uintptr_t) * 8) +#define REGION_MAP_WORDS (REGION_MAP_LIMIT / REGION_SIZE / REGION_MAP_WORD_BITS) + +static PONY_ATOMIC(uintptr_t) region_map[REGION_MAP_WORDS]; + +/// Whether the region map covers addr. On a 32-bit target it covers every +/// address; the gate avoids the comparison, which is always true there and +/// which GCC rejects with -Wtype-limits. +static bool region_map_covers(uintptr_t addr) +{ +#ifdef PLATFORM_IS_ILP32 + (void)addr; + return true; +#else + return (uint64_t)addr < REGION_MAP_LIMIT; +#endif +} + +static void region_map_add(region_t* region) +{ + uintptr_t addr = (uintptr_t)region; + + if(!region_map_covers(addr)) + return; + + size_t index = addr / REGION_SIZE; + PONY_ATOMIC(uintptr_t)* word = ®ion_map[index / REGION_MAP_WORD_BITS]; + uintptr_t bit = (uintptr_t)1 << (index % REGION_MAP_WORD_BITS); + uintptr_t old = atomic_load_explicit(word, memory_order_relaxed); + + while(!atomic_compare_exchange_weak_explicit(word, &old, old | bit, + memory_order_release, memory_order_relaxed)) + ; +} + +/// Whether region is the start of a region this pool created. +static bool region_known(region_t* region) +{ + uintptr_t addr = (uintptr_t)region; + + if(region_map_covers(addr)) + { + size_t index = addr / REGION_SIZE; + uintptr_t word = atomic_load_explicit( + ®ion_map[index / REGION_MAP_WORD_BITS], memory_order_acquire); + return (word & ((uintptr_t)1 << (index % REGION_MAP_WORD_BITS))) != 0; + } + + region_t* r = atomic_load_explicit(®ions_head, memory_order_acquire); + + while((r != NULL) && (r != region)) + r = r->next; + + return r != NULL; +} + /// The header at the start of every arena. Only the owner writes any of it. /// The first cache line holds only the fields every foreign free reads and /// nothing the owner writes after creation, so owner writes at slab cadence @@ -574,6 +642,57 @@ static char* unit_base(arena_t* arena, arena_unit_t* rec) return (char*)arena + (index << UNIT_BITS); } +void* ponyint_pool_base(void* p) +{ + // Arena metadata is read only after the address is found in a known region. + // Regions are never unmapped, so a region's header stays readable; a + // released arena's pages can be decommitted (on Windows, unreadable), which + // is why p must point into a live allocation. + uintptr_t addr = (uintptr_t)p; + region_t* region = (region_t*)(addr & ~(uintptr_t)REGION_MASK); + + if(!region_known(region)) + return NULL; + + size_t slot = (addr & REGION_MASK) / ARENA_SIZE; + uint32_t slots = atomic_load_explicit(®ion->slots, memory_order_acquire); + + if((slot == 0) || ((slots & ((uint32_t)1 << slot)) == 0)) + return NULL; + + // A unit of a live slab keeps its state, span and size class until the + // slab is released, so another thread can read them while the owner + // allocates from the slab. + arena_t* arena = arena_of(p); + size_t index = unit_index(arena, p); + + if((arena->kind != MAPPING_ARENA) || (index < arena_header_units())) + return NULL; + + arena_unit_t* rec = &arena->units[index]; + + if(rec->state == UNIT_STATE_CONT) + rec -= rec->head_offset; + + if(rec->state != UNIT_STATE_HEAD) + return NULL; + + char* base = unit_base(arena, rec); + + if(rec->size_class == SLAB_CLASS_BLOCK) + return base; + + // A slab starts on a unit boundary and holds objects of one power-of-two + // size, so an object starts at a multiple of that size. A slab of a size + // class at least as large as a unit holds one object. + size_t size = class_size(rec->size_class); + + if(size >= UNIT_SIZE) + return base; + + return base + ((addr - (uintptr_t)base) & ~(uintptr_t)(size - 1)); +} + static void bitmap_set(arena_t* arena, size_t from, size_t count) { for(size_t i = from; i < (from + count); i++) @@ -862,6 +981,7 @@ static arena_t* region_create() region->kind = MAPPING_REGION; atomic_store_explicit(®ion->slots, (uint32_t)0x3, memory_order_relaxed); + region_map_add(region); region_t* head = atomic_load_explicit(®ions_head, memory_order_relaxed); @@ -1938,6 +2058,14 @@ static void oversized_free(void* p) ponyint_virt_free(over, over->reserved); } +bool ponyint_pool_size_in_arena(size_t size) +{ + if(ponyint_pool_index(size) < POOL_COUNT) + return true; + + return ponyint_pool_adjust_size(size) <= arena_capacity(); +} + void* ponyint_pool_alloc_size(size_t size) { size_t index = ponyint_pool_index(size); diff --git a/src/libponyrt/mem/pool_memalign.c b/src/libponyrt/mem/pool_memalign.c index 0cb6c6de8b2..f69f5a0e7dd 100644 --- a/src/libponyrt/mem/pool_memalign.c +++ b/src/libponyrt/mem/pool_memalign.c @@ -141,6 +141,18 @@ void ponyint_pool_set_memory_profile(uint32_t rung) (void)rung; } +void* ponyint_pool_base(void* p) +{ + (void)p; + return NULL; +} + +bool ponyint_pool_size_in_arena(size_t size) +{ + (void)size; + return false; +} + void ponyint_pool_drain() { } diff --git a/src/libponyrt/pony.h b/src/libponyrt/pony.h index b953f8ef06e..604c8b76813 100644 --- a/src/libponyrt/pony.h +++ b/src/libponyrt/pony.h @@ -108,6 +108,10 @@ typedef const struct _pony_type_t uint32_t size; uint32_t field_count; uint32_t field_offset; + // For a primitive other than a machine word, its instance (for a bare + // lambda, its function). For a struct, the type of the embedded field with a + // non-zero size at the struct's start, if there is one: the two objects share + // an address. Otherwise NULL. void* instance; char* name; pony_behavior_name_fn get_behavior_name; @@ -116,6 +120,8 @@ typedef const struct _pony_type_t pony_final_fn final; uint32_t event_notify; bool might_reference_actor; + // Flags that only the compiler and the runtime use. + uint8_t embed_flags; uintptr_t** traits; void* fields; void* vtable; @@ -197,6 +203,20 @@ PONY_API ATTRIBUTE_MALLOC void* pony_alloc_small(pony_ctx_t* ctx, uint32_t sizec /// Allocate when we know it's larger than HEAP_MAX. PONY_API ATTRIBUTE_MALLOC void* pony_alloc_large(pony_ctx_t* ctx, size_t size); +/** Allocate a struct that starts with an embedded field with a non-zero size. + * + * Use pony_alloc_small_shared_start in place of pony_alloc_small for such a + * struct, and pony_alloc_large_shared_start in place of pony_alloc_large. The + * struct must not need a finaliser. A struct allocated any other way can have + * its other fields freed while still reachable. + */ +PONY_API ATTRIBUTE_MALLOC void* pony_alloc_small_shared_start(pony_ctx_t* ctx, + uint32_t sizeclass); + +/// As pony_alloc_small_shared_start, when the struct is larger than HEAP_MAX. +PONY_API ATTRIBUTE_MALLOC void* pony_alloc_large_shared_start(pony_ctx_t* ctx, + size_t size); + /** Reallocate memory on the current actor's heap. * * Take heap memory and expand it. This is a no-op if there's already enough @@ -283,13 +303,23 @@ enum /** Trace memory * * Call this on allocated blocks of memory that do not have object headers. + * Call it also for a pointer that can point at an object of any type, such as + * a Pony Pointer, which has no trace function of its own. The memory is traced + * as opaque and with no type. */ PONY_API void pony_trace(pony_ctx_t* ctx, void* p); -/** Trace an object. +/** Trace an object of a type that isn't routed. * - * This should be called for every pointer field in an object when the object's - * trace function is invoked. + * A routed type is one whose objects can share an address with an object of + * another type: a type embedded at the start of a struct, a struct that starts + * with an embedded field, a type with no size that is embedded somewhere (such + * a field has its holder's address), or a class or struct that embeds a field + * with no size. Whether a type is routed depends on the whole program it is + * compiled into, so C code that traces a Pony object should call + * pony_traceknown_routed, which takes any type. An actor's type is never + * routed, so C code can trace an actor with this. Called with a routed type, + * this can let the GC free a struct's fields while they are still reachable. * * @param ctx The current context. * @param p The pointer being traced. @@ -298,9 +328,30 @@ PONY_API void pony_trace(pony_ctx_t* ctx, void* p); */ PONY_API void pony_traceknown(pony_ctx_t* ctx, void* p, pony_type_t* t, int m); -/** Trace unknown. +/** Trace an object of a routed type (see pony_traceknown). + * + * Use this in place of pony_traceknown when t is routed. It also takes any + * other type, at the cost of reading t's embed_flags, so C code that can't know + * whether t is routed calls this. An object of a routed type with no size has + * the address of the object that holds it, and is traced as opaque whatever m + * is. + * + * @param ctx The current context. + * @param p The pointer being traced. + * @param t The pony_type_t for the object pointed to. + * @param m Logical mutability of the object pointed to. + */ +PONY_API void pony_traceknown_routed(pony_ctx_t* ctx, void* p, + pony_type_t* t, int m); + +/** Trace a field of unknown type that can't hold a routed type (see + * pony_traceknown). * - * This should be called for fields in an object with an unknown type. + * Whether a type is routed depends on the whole program, so C code should call + * pony_traceunknown_routed, which takes any type. An actor's type is never + * routed, so C code can trace an actor with this. Called where a routed type + * can be traced, this can let the GC free a struct's fields while they are + * still reachable. * * @param ctx The current context. * @param p The pointer being traced. @@ -308,6 +359,19 @@ PONY_API void pony_traceknown(pony_ctx_t* ctx, void* p, pony_type_t* t, int m); */ PONY_API void pony_traceunknown(pony_ctx_t* ctx, void* p, int m); +/** Trace a field of unknown type that can hold a routed type (see + * pony_traceknown). + * + * Use this in place of pony_traceunknown when one of the types the field can + * hold is routed. It also takes an object of any other type, so C code that + * can't know whether a type is routed calls this. + * + * @param ctx The current context. + * @param p The pointer being traced. + * @param m Logical mutability of the object pointed to. + */ +PONY_API void pony_traceunknown_routed(pony_ctx_t* ctx, void* p, int m); + /** Initialize the runtime. * * Call this first. It will strip out command line arguments that you should diff --git a/src/libponyrt/sched/scheduler.c b/src/libponyrt/sched/scheduler.c index 97ba824febe..eada39aa250 100644 --- a/src/libponyrt/sched/scheduler.c +++ b/src/libponyrt/sched/scheduler.c @@ -1390,8 +1390,11 @@ static void ponyint_sched_shutdown() ponyint_gc_maps_destroy(); ponyint_cycle_terminate(&this_scheduler->ctx); + ponyint_gc_free_visits(&this_scheduler->ctx); + for(uint32_t i = 0; i < scheduler_count; i++) { + ponyint_gc_free_visits(&scheduler[i].ctx); while(ponyint_thread_messageq_pop(&scheduler[i].mq) != NULL) { ; } ponyint_mutemap_destroy(&scheduler[i].mute_mapping); ponyint_messageq_destroy(&scheduler[i].mq, false); @@ -1664,6 +1667,7 @@ void ponyint_unregister_thread() if(this_scheduler == NULL) return; + ponyint_gc_free_visits(&this_scheduler->ctx); POOL_FREE(scheduler_t, this_scheduler); this_scheduler = NULL; diff --git a/src/libponyrt/sched/scheduler.h b/src/libponyrt/sched/scheduler.h index c3a9d184351..857cea09761 100644 --- a/src/libponyrt/sched/scheduler.h +++ b/src/libponyrt/sched/scheduler.h @@ -77,6 +77,9 @@ typedef struct pony_ctx_t scheduler_t* scheduler; pony_actor_t* current; trace_object_fn trace_object; + // Used in place of trace_object for a type with PONY_EMBED_ROUTED; set and + // cleared with it. + trace_object_fn trace_routed; trace_actor_fn trace_actor; // Temporary stack for GC tracing; empty when GC not running gcstack_t* stack; @@ -100,6 +103,8 @@ typedef struct pony_ctx_t uint64_t last_tsc; schedulerstats_t schedulerstats; #endif + // The visits a mark recorded, by address and type. Empty between marks. + gc_visitset_t visits; } pony_ctx_t; struct scheduler_t diff --git a/src/libponyrt/sched/start.c b/src/libponyrt/sched/start.c index 30f3f562c3f..41e61ab010a 100644 --- a/src/libponyrt/sched/start.c +++ b/src/libponyrt/sched/start.c @@ -7,6 +7,7 @@ #include "../mem/pool.h" #include "../actor/actor.h" #include "../gc/cycle.h" +#include "../gc/sections.h" #include "../lang/process.h" #include "../lang/socket.h" #include "../lang/stdfd.h" @@ -420,6 +421,7 @@ PONY_API int pony_init(int argc, char** argv) opt.tracing_flight_recorder_handle_term_int = false; opt.pintracing = false; + ponyint_section_bounds_init(); ponyint_register_thread(); // Allow override via bare function on Main actor diff --git a/test/full-program-tests/constant-section/expected-exit-code.txt b/test/full-program-tests/constant-section/expected-exit-code.txt new file mode 100644 index 00000000000..d00491fd7e5 --- /dev/null +++ b/test/full-program-tests/constant-section/expected-exit-code.txt @@ -0,0 +1 @@ +1 diff --git a/test/full-program-tests/constant-section/main.pony b/test/full-program-tests/constant-section/main.pony new file mode 100644 index 00000000000..0dc5554656c --- /dev/null +++ b/test/full-program-tests/constant-section/main.pony @@ -0,0 +1,41 @@ +// Descriptors are in the descriptor section and the other objects the compiler +// emits as constants in the constant section, whose bounds the runtime reads; +// objects made at run time are in neither. The program also checks that both +// sections are read-only once the program is loaded. +// The program exits 1 only if every check holds, and otherwise 10 plus the +// number of the first check that fails. +use @shim_constant[I32](p: Any tag) +use @shim_descriptor[I32](p: Any tag) +use @shim_outside_descriptors[I32](p: Any tag) +use @shim_section_read_only[I32]() + +primitive P + +actor Main + new create(env: Env) => + let literal = "literal" + let heap = String .> append("x") + let bytes: Array[U8] val = recover val [as U8: 1; 2; 3] end + let checks: Array[Bool] = [ + @shim_constant(literal) == 1 + @shim_constant(P) == 1 + @shim_constant(bytes) == 1 + @shim_constant(heap) == 0 + @shim_constant(this) == 0 + @shim_descriptor(literal) == 1 + @shim_descriptor(heap) == 1 + @shim_descriptor(this) == 1 + @shim_outside_descriptors(literal) == 1 + @shim_outside_descriptors(P) == 1 + @shim_section_read_only() == 1 + ] + var code: I32 = 1 + var n: I32 = 0 + for ok in checks.values() do + n = n + 1 + if not ok then + code = 10 + n + break + end + end + env.exitcode(code) diff --git a/test/full-program-tests/constant-section/shim.c b/test/full-program-tests/constant-section/shim.c new file mode 100644 index 00000000000..da5a034a827 --- /dev/null +++ b/test/full-program-tests/constant-section/shim.c @@ -0,0 +1,89 @@ +#include +#if defined(_WIN32) +#include +#else +#include +#include +#endif + +/* The bounds that ponyint_section_bounds_init sets (gc/sections.c). */ +extern uintptr_t ponyint_const_section_start; +extern uintptr_t ponyint_const_section_end; +extern uintptr_t ponyint_desc_section_start; +extern uintptr_t ponyint_desc_section_end; + +static int32_t in_range(const void* p, uintptr_t start, uintptr_t end) +{ + return ((uintptr_t)p - start) < (end - start); +} + +int32_t shim_constant(const void* object) +{ + return in_range(object, ponyint_const_section_start, + ponyint_const_section_end); +} + +/* Whether the object's descriptor is in the descriptor section, and not in + * the constant section. */ +int32_t shim_descriptor(const void* object) +{ + const void* desc = *(const void* const*)object; + + return in_range(desc, ponyint_desc_section_start, ponyint_desc_section_end) && + !in_range(desc, ponyint_const_section_start, ponyint_const_section_end); +} + +/* Whether the object is outside the descriptor section. */ +int32_t shim_outside_descriptors(const void* object) +{ + return !in_range(object, ponyint_desc_section_start, + ponyint_desc_section_end); +} + +/* Whether the page holding p is mapped without write access. */ +static int32_t page_read_only(char* p) +{ +#if defined(_WIN32) + MEMORY_BASIC_INFORMATION info; + + if(VirtualQuery(p, &info, sizeof(info)) == 0) + return 0; + + return (info.Protect & (PAGE_READWRITE | PAGE_WRITECOPY | + PAGE_EXECUTE_READWRITE | PAGE_EXECUTE_WRITECOPY)) == 0; +#else + // read() into a page without write access fails with EFAULT instead of + // raising a signal. If the page is writable, read() stores the byte write() + // just copied from it, so the page is unchanged. + int fds[2]; + + if(pipe(fds) != 0) + return 0; + + int32_t read_only = 0; + + if(write(fds[1], p, 1) == 1) + read_only = (read(fds[0], p, 1) == -1) && (errno == EFAULT); + + close(fds[0]); + close(fds[1]); + return read_only; +#endif +} + +/* Whether the pages holding a range's first and last bytes are mapped without + * write access. */ +static int32_t range_read_only(uintptr_t start, uintptr_t end) +{ + if((start == 0) || (end <= start)) + return 0; + + return page_read_only((char*)start) && page_read_only((char*)end - 1); +} + +int32_t shim_section_read_only(void) +{ + return range_read_only(ponyint_const_section_start, + ponyint_const_section_end) && + range_read_only(ponyint_desc_section_start, ponyint_desc_section_end); +} diff --git a/test/full-program-tests/embed-empty-field-address/main.pony b/test/full-program-tests/embed-empty-field-address/main.pony new file mode 100644 index 00000000000..cf518effcc3 --- /dev/null +++ b/test/full-program-tests/embed-empty-field-address/main.pony @@ -0,0 +1,53 @@ +// An embedded struct with no size has the address of the object that holds +// it, wherever it is declared, so its address is always inside that object. +struct Z + new create() => None + +// No size either, though it has a field. +struct B + embed z: Z = Z + new create() => None + +class C + var x: U64 = 0 + embed z: Z = Z + +struct S + var x: U64 = 0 + embed z: Z = Z + new create() => None + +struct \packed\ P + var x: U8 = 0 + embed z: Z = Z + new create() => None + +class M + embed z: Z = Z + var x: U64 = 0 + +class N + var x: U64 = 0 + embed b: B = B + +actor Main + embed z: Z = Z + embed b: B = B + + new create(env: Env) => + let c = C + let s = S + let p = P + let m = M + let n = N + if ((digestof c.z) != (digestof c)) or + ((digestof s.z) != (digestof s)) or + ((digestof p.z) != (digestof p)) or + ((digestof m.z) != (digestof m)) or + ((digestof n.b) != (digestof n)) or + ((digestof n.b.z) != (digestof n)) or + ((digestof z) != (digestof this)) or + ((digestof b) != (digestof this)) + then + env.exitcode(1) + end diff --git a/test/full-program-tests/embed-gc-acquire-embedded-struct-forward/main.pony b/test/full-program-tests/embed-gc-acquire-embedded-struct-forward/main.pony new file mode 100644 index 00000000000..8fcae5c271e --- /dev/null +++ b/test/full-program-tests/embed-gc-acquire-embedded-struct-forward/main.pony @@ -0,0 +1,34 @@ +// Another actor reaches an embedded struct through a val object, acquires it +// from the owner, and passes it on to a third actor. The owner's next +// collection must not crash. +use @pony_ctx[Pointer[None]]() +use @pony_triggergc[None](ctx: Pointer[None]) + +struct S + var x: U64 = 5 + new create() => None + +class O + embed s: S = S + +actor Keeper + var _s: S val = recover S end + be take(s: S val) => _s = s + +actor Forwarder + var _o: (O val | None) = None + be take(o: O val, main: Main) => + _o = o + Keeper.take(o.s) + main.collect() + +actor Main + var _o: (O val | None) = None + new create(env: Env) => + let o: O val = recover O end + _o = o + Forwarder.take(o, this) + be collect() => + @pony_triggergc(@pony_ctx()) + check() + be check() => None diff --git a/test/full-program-tests/embed-gc-acquire-embedded-struct-hold/main.pony b/test/full-program-tests/embed-gc-acquire-embedded-struct-hold/main.pony new file mode 100644 index 00000000000..b99ae1478ab --- /dev/null +++ b/test/full-program-tests/embed-gc-acquire-embedded-struct-hold/main.pony @@ -0,0 +1,34 @@ +// Another actor reaches an embedded struct through a val object, acquires it +// from the owner, keeps it, and collects. The owner's next collection must +// not crash. +use @pony_ctx[Pointer[None]]() +use @pony_triggergc[None](ctx: Pointer[None]) + +struct S + var x: U64 = 5 + new create() => None + +class O + embed s: S = S + +actor Holder + var _o: (O val | None) = None + var _s: S val = recover S end + be take(o: O val, main: Main) => + _o = o + _s = o.s + @pony_triggergc(@pony_ctx()) + step(main) + be step(main: Main) => + main.collect() + +actor Main + var _o: (O val | None) = None + new create(env: Env) => + let o: O val = recover O end + _o = o + Holder.take(o, this) + be collect() => + @pony_triggergc(@pony_ctx()) + check() + be check() => None diff --git a/test/full-program-tests/embed-gc-actor-field-cycle/main.pony b/test/full-program-tests/embed-gc-actor-field-cycle/main.pony new file mode 100644 index 00000000000..cfb8147f1e1 --- /dev/null +++ b/test/full-program-tests/embed-gc-actor-field-cycle/main.pony @@ -0,0 +1,19 @@ +// An actor's embedded field references itself. The actor's own collection +// reaches the field through a pointer into the actor and must finish. +use @pony_ctx[Pointer[None]]() +use @pony_triggergc[None](ctx: Pointer[None]) + +class C + var self_ref: (C | None) = None + +actor Main + embed c: C = C + + new create(env: Env) => + c.self_ref = c + String(64) + @pony_triggergc(@pony_ctx()) + check() + + be check() => + None diff --git a/test/full-program-tests/embed-gc-actor-nested-embed-cycle/main.pony b/test/full-program-tests/embed-gc-actor-nested-embed-cycle/main.pony new file mode 100644 index 00000000000..1a13460f2b0 --- /dev/null +++ b/test/full-program-tests/embed-gc-actor-nested-embed-cycle/main.pony @@ -0,0 +1,22 @@ +// An actor embeds E, which embeds F; F references itself. The actor's +// collection must finish. +use @pony_ctx[Pointer[None]]() +use @pony_triggergc[None](ctx: Pointer[None]) + +class F + var self_ref: (F | None) = None + +class E + embed f: F = F + +actor Main + embed e: E = E + + new create(env: Env) => + e.f.self_ref = e.f + String(64) + @pony_triggergc(@pony_ctx()) + check() + + be check() => + None diff --git a/test/full-program-tests/embed-gc-actor-outlives-field-holder/main.pony b/test/full-program-tests/embed-gc-actor-outlives-field-holder/main.pony new file mode 100644 index 00000000000..5b8d7c4b9a6 --- /dev/null +++ b/test/full-program-tests/embed-gc-actor-outlives-field-holder/main.pony @@ -0,0 +1,47 @@ +// Actors send their embedded val field and then have nothing left to do. +// While another actor holds the fields, the sending actors must not be +// collected: their memory would be reused by the actors created afterwards. +class C + let n: U64 + new val create(n': U64) => n = n' + +actor Donor + embed c: C val = C(0xDEADBEEF) + new create(k: Keeper) => + k.take(c) + +actor Filler + // Same layout as Donor, so a Filler can reuse a freed Donor's memory. + embed c: C val = C(0x1111) + new create() => None + +actor Keeper + let _cs: Array[C val] = Array[C val] + var _bad: U64 = 0 + let _env: Env + + new create(env: Env) => _env = env + + be take(c: C val) => + _cs.push(c) + + be churn(i: U64) => + var k: USize = 0 + while k < 200 do + Filler + k = k + 1 + end + for c in _cs.values() do + if c.n != 0xDEADBEEF then _bad = _bad + 1 end + end + if i < 1000 then churn(i + 1) elseif _bad != 0 then _env.exitcode(1) end + +actor Main + new create(env: Env) => + let k = Keeper(env) + var d: USize = 0 + while d < 10 do + Donor(k) + d = d + 1 + end + k.churn(0) diff --git a/test/full-program-tests/embed-gc-actor-outlives-field-holder/program-args.txt b/test/full-program-tests/embed-gc-actor-outlives-field-holder/program-args.txt new file mode 100644 index 00000000000..7469a4aa9f2 --- /dev/null +++ b/test/full-program-tests/embed-gc-actor-outlives-field-holder/program-args.txt @@ -0,0 +1 @@ +--ponycdinterval=10 diff --git a/test/full-program-tests/embed-gc-actor-struct-start-own/main.pony b/test/full-program-tests/embed-gc-actor-struct-start-own/main.pony new file mode 100644 index 00000000000..ae68fdf9be8 --- /dev/null +++ b/test/full-program-tests/embed-gc-actor-struct-start-own/main.pony @@ -0,0 +1,48 @@ +// Main embeds a struct that starts with an embedded field and holds that field +// in another field. Main's collections reach the struct's address as the +// field, with no heap chunk to record it. The struct's other field must still +// be traced. +use @pony_ctx[Pointer[None]]() +use @pony_triggergc[None](ctx: Pointer[None]) + +class C + var x: U64 = 7 + +class D + let n: U64 + + new create(n': U64) => + n = n' + +struct S + embed c: C = C + var d: D = D(0xDEADBEEF) + + new create() => + None + +actor Main + embed s: S = S + var _c: C + var _last: D = D(0) + var _bad: U64 = 0 + let _env: Env + + new create(env: Env) => + _env = env + _c = s.c + churn(0) + + be churn(i: U64) => + var k: USize = 0 + while k < 2000 do + _last = D(i) + k = k + 1 + end + @pony_triggergc(@pony_ctx()) + if s.d.n != 0xDEADBEEF then _bad = _bad + 1 end + if i < 50 then + churn(i + 1) + elseif _bad != 0 then + _env.exitcode(1) + end diff --git a/test/full-program-tests/embed-gc-actor-struct-start-send/main.pony b/test/full-program-tests/embed-gc-actor-struct-start-send/main.pony new file mode 100644 index 00000000000..594711e2112 --- /dev/null +++ b/test/full-program-tests/embed-gc-actor-struct-start-send/main.pony @@ -0,0 +1,78 @@ +// Donor actors embed a struct that starts with an embedded field. Each sends +// the field and the struct to a keeper and finishes. Neither is in a heap +// chunk, so the keeper's references must keep each donor alive while the +// keeper still holds them. +class C + let x: U64 + + new val create(x': U64) => + x = x' + +class D + let n: U64 + + new val create(n': U64) => + n = n' + +struct S + embed c: C val = C(7) + let d: D val + + new val create(d': D val) => + d = d' + +actor Donor + embed s: S val = S(D(0xDEADBEEF)) + + new create(k: Keeper) => + k.take(s.c, s) + +actor Filler + embed s: S val = S(D(0x1111)) + + new create() => + None + +actor Keeper + let _cs: Array[C val] = Array[C val] + let _ss: Array[S val] = Array[S val] + var _bad: U64 = 0 + let _env: Env + + new create(env: Env) => + _env = env + + be take(c: C val, s: S val) => + _cs.push(c) + _ss.push(s) + + be churn(i: U64) => + var k: USize = 0 + while k < 200 do + Filler + k = k + 1 + end + for s in _ss.values() do + if s.d.n != 0xDEADBEEF then _bad = _bad + 1 end + end + for c in _cs.values() do + if c.x != 7 then _bad = _bad + 1 end + end + if i < 300 then + churn(i + 1) + elseif _bad != 0 then + _env.exitcode(1) + end + +actor Main + new create(env: Env) => + let k = Keeper(env) + var d: USize = 0 + while d < 10 do + Donor(k) + d = d + 1 + end + k.churn(0) + + fun @runtime_override_defaults(rto: RuntimeOptions) => + rto.ponycdinterval = 10 diff --git a/test/full-program-tests/embed-gc-actor-too-large-for-an-arena/main.pony b/test/full-program-tests/embed-gc-actor-too-large-for-an-arena/main.pony new file mode 100644 index 00000000000..5accdd65a28 --- /dev/null +++ b/test/full-program-tests/embed-gc-actor-too-large-for-an-arena/main.pony @@ -0,0 +1,145 @@ +// Actors larger than an arena (S4 is 8 MiB) send their embedded String to a +// Reader and have nothing left to do. While the Reader holds the Strings, the +// actors must not be collected: their memory would be returned to the system. +struct S0 + var f0: U64 = 0 + var f1: U64 = 0 + var f2: U64 = 0 + var f3: U64 = 0 + var f4: U64 = 0 + var f5: U64 = 0 + var f6: U64 = 0 + var f7: U64 = 0 + var f8: U64 = 0 + var f9: U64 = 0 + var f10: U64 = 0 + var f11: U64 = 0 + var f12: U64 = 0 + var f13: U64 = 0 + var f14: U64 = 0 + var f15: U64 = 0 + new create() => None + +struct S1 + embed f0: S0 = S0 + embed f1: S0 = S0 + embed f2: S0 = S0 + embed f3: S0 = S0 + embed f4: S0 = S0 + embed f5: S0 = S0 + embed f6: S0 = S0 + embed f7: S0 = S0 + embed f8: S0 = S0 + embed f9: S0 = S0 + embed f10: S0 = S0 + embed f11: S0 = S0 + embed f12: S0 = S0 + embed f13: S0 = S0 + embed f14: S0 = S0 + embed f15: S0 = S0 + new create() => None + +struct S2 + embed f0: S1 = S1 + embed f1: S1 = S1 + embed f2: S1 = S1 + embed f3: S1 = S1 + embed f4: S1 = S1 + embed f5: S1 = S1 + embed f6: S1 = S1 + embed f7: S1 = S1 + embed f8: S1 = S1 + embed f9: S1 = S1 + embed f10: S1 = S1 + embed f11: S1 = S1 + embed f12: S1 = S1 + embed f13: S1 = S1 + embed f14: S1 = S1 + embed f15: S1 = S1 + new create() => None + +struct S3 + embed f0: S2 = S2 + embed f1: S2 = S2 + embed f2: S2 = S2 + embed f3: S2 = S2 + embed f4: S2 = S2 + embed f5: S2 = S2 + embed f6: S2 = S2 + embed f7: S2 = S2 + embed f8: S2 = S2 + embed f9: S2 = S2 + embed f10: S2 = S2 + embed f11: S2 = S2 + embed f12: S2 = S2 + embed f13: S2 = S2 + embed f14: S2 = S2 + embed f15: S2 = S2 + new create() => None + +struct S4 + embed f0: S3 = S3 + embed f1: S3 = S3 + embed f2: S3 = S3 + embed f3: S3 = S3 + embed f4: S3 = S3 + embed f5: S3 = S3 + embed f6: S3 = S3 + embed f7: S3 = S3 + embed f8: S3 = S3 + embed f9: S3 = S3 + embed f10: S3 = S3 + embed f11: S3 = S3 + embed f12: S3 = S3 + embed f13: S3 = S3 + embed f14: S3 = S3 + embed f15: S3 = S3 + new create() => None + + +actor Holder + embed big: S4 = S4 + embed big2: S1 = S1 + embed s: String val = String.from_array(recover val + [as U8: 'h'; 'e'; 'l'; 'l'; 'o'] end) + + new create(r: Reader) => + r.take(s) + +actor Reader + let _env: Env + var _s: (String val | None) = None + + new create(env: Env) => + _env = env + + be take(s: String val) => + _s = s + spin(0) + + be spin(i: USize) => + if i < 4000 then + spin(i + 1) + else + match _s + | let s: String val => + if s != "hello" then _env.exitcode(1) end + end + end + +actor Churn + new create(n: USize) => + if n > 0 then + Churn(n - 1) + end + Array[U8].create(1000) + +actor Main + new create(env: Env) => + let r = Reader(env) + var i: USize = 0 + while i < 12 do + Holder(r) + i = i + 1 + end + Churn(1000) diff --git a/test/full-program-tests/embed-gc-actor-too-large-for-an-arena/program-args.txt b/test/full-program-tests/embed-gc-actor-too-large-for-an-arena/program-args.txt new file mode 100644 index 00000000000..7469a4aa9f2 --- /dev/null +++ b/test/full-program-tests/embed-gc-actor-too-large-for-an-arena/program-args.txt @@ -0,0 +1 @@ +--ponycdinterval=10 diff --git a/test/full-program-tests/embed-gc-actor-val-field-send/main.pony b/test/full-program-tests/embed-gc-actor-val-field-send/main.pony new file mode 100644 index 00000000000..58b0a547346 --- /dev/null +++ b/test/full-program-tests/embed-gc-actor-val-field-send/main.pony @@ -0,0 +1,28 @@ +// An actor sends its embedded val field, which references itself. Tracing the +// message must finish, and the receiver can collect while holding it. +use @pony_ctx[Pointer[None]]() +use @pony_triggergc[None](ctx: Pointer[None]) + +class C + var self_ref: (C box | None) = None + let n: U64 = 7 + new val create() => self_ref = this + +actor Keeper + var _c: (C val | None) = None + let _env: Env + new create(env: Env) => _env = env + be take(c: C val) => + _c = c + @pony_triggergc(@pony_ctx()) + check() + be check() => + match _c + | let c: C val => if c.n != 7 then _env.exitcode(1) end + end + +actor Main + embed c: C val = C + + new create(env: Env) => + Keeper(env).take(c) diff --git a/test/full-program-tests/embed-gc-class-field-only/main.pony b/test/full-program-tests/embed-gc-class-field-only/main.pony new file mode 100644 index 00000000000..86315037ad3 --- /dev/null +++ b/test/full-program-tests/embed-gc-class-field-only/main.pony @@ -0,0 +1,42 @@ +// Main keeps only an embedded field from the middle of an object, not the +// object that holds it. The field's own references must still be traced. +class D + let n: U64 + + new create(n': U64) => + n = n' + +class C + var d: D = D(0xDEADBEEF) + +class A + var x: U64 = 0 + embed c: C = C + +actor Main + let _c: C + var _last: A = A + var _bad: U64 = 0 + let _env: Env + + new create(env: Env) => + _env = env + let a: A ref = A + _c = a.c + churn(0) + + be churn(i: U64) => + var k: USize = 0 + while k < 2000 do + let a: A ref = A + a.x = i + a.c.d = D(i) + _last = a + k = k + 1 + end + if _c.d.n != 0xDEADBEEF then _bad = _bad + 1 end + if i < 200 then + churn(i + 1) + elseif _bad != 0 then + _env.exitcode(1) + end diff --git a/test/full-program-tests/embed-gc-embedded-field-cycle/main.pony b/test/full-program-tests/embed-gc-embedded-field-cycle/main.pony new file mode 100644 index 00000000000..45eb86d8ab9 --- /dev/null +++ b/test/full-program-tests/embed-gc-embedded-field-cycle/main.pony @@ -0,0 +1,35 @@ +// Embedded objects that reference themselves, or each other, form cycles that +// a collection reaches through pointers into the middle of their allocations. +// The collection must finish. +class C + var other: (C | None) = None + var n: U64 = 7 + +class A + embed c: C = C + +actor Main + var _self: C + var _pair: C + var _i: USize = 0 + + new create(env: Env) => + let a: A ref = A + a.c.other = a.c + _self = a.c + let b: A ref = A + let d: A ref = A + b.c.other = d.c + d.c.other = b.c + _pair = b.c + churn() + + be churn() => + var k: USize = 0 + while k < 1000 do + let s = String(64) + s.append("abcdefgh") + k = k + 1 + end + _i = _i + 1 + if _i < 50 then churn() end diff --git a/test/full-program-tests/embed-gc-large-struct-field-first-mark/main.pony b/test/full-program-tests/embed-gc-large-struct-field-first-mark/main.pony new file mode 100644 index 00000000000..c9c2c83290e --- /dev/null +++ b/test/full-program-tests/embed-gc-large-struct-field-first-mark/main.pony @@ -0,0 +1,71 @@ +// A struct's first embedded field shares the struct's address, and the struct +// is too large for a small heap chunk. Main declares the field before the +// struct, so its collection reaches the address as the field first. The +// struct's other field must still be traced. +class C + let x: U64 = 7 + +class D + let n: U64 + + new create(n': U64) => + n = n' + +struct Pad + var p0: U64 = 0 + var p1: U64 = 0 + var p2: U64 = 0 + var p3: U64 = 0 + var p4: U64 = 0 + var p5: U64 = 0 + var p6: U64 = 0 + var p7: U64 = 0 + var p8: U64 = 0 + var p9: U64 = 0 + var p10: U64 = 0 + var p11: U64 = 0 + var p12: U64 = 0 + var p13: U64 = 0 + var p14: U64 = 0 + var p15: U64 = 0 + + new create() => + None + +struct S + embed c: C = C + embed pad0: Pad = Pad + embed pad1: Pad = Pad + embed pad2: Pad = Pad + embed pad3: Pad = Pad + embed pad4: Pad = Pad + let d: D + + new create(d': D) => + d = d' + +actor Main + let _c: C + let _s: S + var _last: D = D(0) + var _bad: U64 = 0 + let _env: Env + + new create(env: Env) => + _env = env + _s = S(D(0xDEADBEEF)) + _c = _s.c + churn(0) + + be churn(i: U64) => + var k: USize = 0 + while k < 2000 do + _last = D(i) + k = k + 1 + end + if _s.d.n != 0xDEADBEEF then _bad = _bad + 1 end + if i < 200 then + churn(i + 1) + elseif _bad != 0 then + _env.exitcode(1) + end diff --git a/test/full-program-tests/embed-gc-nested-struct-start-local/main.pony b/test/full-program-tests/embed-gc-nested-struct-start-local/main.pony new file mode 100644 index 00000000000..3b41b9b720d --- /dev/null +++ b/test/full-program-tests/embed-gc-nested-struct-start-local/main.pony @@ -0,0 +1,45 @@ +// S2 starts with S1, which starts with C, so all three share an address. +// Main keeps C, S1 and S2. Each one's own field must survive. +class D + let n: U64 + new create(n': U64) => n = n' + +class C + var e: D = D(0xDEADBEEF) + +struct S1 + embed c: C = C + var d: D = D(0xDEADBEEF) + new create() => None + +struct S2 + embed s: S1 = S1 + var f: D = D(0xDEADBEEF) + new create() => None + +actor Main + let _c: C + let _s1: S1 + let _s2: S2 + var _last: D = D(0) + var _bad: U64 = 0 + let _env: Env + + new create(env: Env) => + _env = env + let s2 = S2 + _c = s2.s.c + _s1 = s2.s + _s2 = s2 + churn(0) + + be churn(i: U64) => + var k: USize = 0 + while k < 2000 do + _last = D(i) + k = k + 1 + end + if _c.e.n != 0xDEADBEEF then _bad = _bad + 1 end + if _s1.d.n != 0xDEADBEEF then _bad = _bad + 1 end + if _s2.f.n != 0xDEADBEEF then _bad = _bad + 1 end + if i < 200 then churn(i + 1) elseif _bad != 0 then _env.exitcode(1) end diff --git a/test/full-program-tests/embed-gc-nested-struct-start-message/main.pony b/test/full-program-tests/embed-gc-nested-struct-start-message/main.pony new file mode 100644 index 00000000000..6bc3a6c58ee --- /dev/null +++ b/test/full-program-tests/embed-gc-nested-struct-start-message/main.pony @@ -0,0 +1,58 @@ +// S2 starts with S1, which starts with C. C and S2 go in one message, C first. +// The receiver's collections must trace S2's field e. +class C + let x: U64 = 7 + +class D + let n: U64 + new create(n': U64) => n = n' + +struct S1 + embed c: C = C + var x: U64 = 0 + new create() => None + +struct S2 + embed s: S1 = S1 + let e: D + new create(e': D iso) => e = consume e' + +actor Receiver + var _c: C val + var _s: S2 val + let _env: Env + var _bad: U64 = 0 + new create(env: Env) => + _env = env + _s = recover S2(recover D(0xDEADBEEF) end) end + _c = _s.s.c + + be take(c: C val, s: S2 val) => + _c = c + _s = s + + be check(i: U64) => + if _s.e.n != 0xDEADBEEF then _bad = _bad + 1 end + if (i == 200) and (_bad != 0) then _env.exitcode(1) end + +actor Sender + let _r: Receiver + var _last: D = D(0) + new create(r: Receiver) => + _r = r + let s: S2 val = recover S2(recover D(0xDEADBEEF) end) end + _r.take(s.s.c, s) + + be churn(i: U64) => + var k: USize = 0 + while k < 2000 do + _last = D(i) + k = k + 1 + end + _r.check(i) + if i < 200 then churn(i + 1) end + +actor Main + new create(env: Env) => + let r = Receiver(env) + Sender(r).churn(0) diff --git a/test/full-program-tests/embed-gc-pointer-at-struct-start-send/main.pony b/test/full-program-tests/embed-gc-pointer-at-struct-start-send/main.pony new file mode 100644 index 00000000000..66a14052a5a --- /dev/null +++ b/test/full-program-tests/embed-gc-pointer-at-struct-start-send/main.pony @@ -0,0 +1,82 @@ +// Main sends a Receiver a holder whose Pointer to the start of a struct comes +// before the struct itself, and the struct starts with an embedded class, so +// its start is shared. The Pointer's visit must not stop the send from tracing +// the struct and the class at its start, or the struct's field isn't counted +// for the Receiver and Main frees it while the Receiver still holds it. +use @memmove[Pointer[U8]](dst: S tag, src: S tag, n: USize) + +class C + var e: D = D(888888) + +class D + let n: U64 + + new create(n': U64) => + n = n' + +struct S + embed c: C = C + var d: D = D(777777) + + new create() => + None + +class Holder + var p: Pointer[U8] + var s: S + + new create() => + let s' = S + p = @memmove(s', s', 0) + s = s' + +actor Receiver + let _env: Env + var _h: Holder = Holder + var _stop: Bool = false + + new create(env: Env) => + _env = env + + be take(h: Holder iso) => + _h = consume h + check() + + be stop() => + _stop = true + + be check() => + var k: USize = 0 + while k < 200 do + D(k.u64()) + k = k + 1 + end + if (_h.s.d.n != 777777) or (_h.s.c.e.n != 888888) then + _env.exitcode(1) + return + end + if not _stop then check() end + +actor Main + var _last: D = D(0) + var _i: USize = 0 + let _r: Receiver + + new create(env: Env) => + _r = Receiver(env) + let h: Holder iso = recover iso Holder end + _r.take(consume h) + churn() + + fun @runtime_override_defaults(rto: RuntimeOptions) => + rto.ponygcinitial = 0 + rto.ponygcfactor = 1.0 + + be churn() => + var k: USize = 0 + while k < 10000 do + _last = D(k.u64()) + k = k + 1 + end + _i = _i + 1 + if _i < 300 then churn() else _r.stop() end diff --git a/test/full-program-tests/embed-gc-pointer-at-struct-start/main.pony b/test/full-program-tests/embed-gc-pointer-at-struct-start/main.pony new file mode 100644 index 00000000000..d881985b70c --- /dev/null +++ b/test/full-program-tests/embed-gc-pointer-at-struct-start/main.pony @@ -0,0 +1,57 @@ +// A class holds a Pointer to the start of a struct before it holds the struct, +// and the struct starts with an embedded class, so its start is shared. The +// Pointer's visit must not stop the visits as the struct and as the class at +// its start from tracing their fields. +use @memmove[Pointer[U8]](dst: S tag, src: S tag, n: USize) + +class C + var e: D = D(888888) + +class D + let n: U64 + + new create(n': U64) => + n = n' + +struct S + embed c: C = C + var d: D = D(777777) + + new create() => + None + +class Holder + var p: Pointer[U8] + var s: S + + new create() => + let s' = S + p = @memmove(s', s', 0) + s = s' + +actor Main + let _env: Env + let _h: Holder = Holder + var _i: USize = 0 + var _last: D = D(0) + + new create(env: Env) => + _env = env + churn() + + fun @runtime_override_defaults(rto: RuntimeOptions) => + rto.ponygcinitial = 0 + rto.ponygcfactor = 1.0 + + be churn() => + var k: USize = 0 + while k < 10000 do + _last = D(k.u64()) + k = k + 1 + end + if (_h.s.d.n != 777777) or (_h.s.c.e.n != 888888) then + _env.exitcode(1) + return + end + _i = _i + 1 + if _i < 50 then churn() end diff --git a/test/full-program-tests/embed-gc-pool-memory-not-an-actor/main.pony b/test/full-program-tests/embed-gc-pool-memory-not-an-actor/main.pony new file mode 100644 index 00000000000..b8c2accd1ad --- /dev/null +++ b/test/full-program-tests/embed-gc-pool-memory-not-an-actor/main.pony @@ -0,0 +1,70 @@ +// Memory from the runtime's pool allocator, obtained through FFI, holds a +// struct. The struct's type is embedded in an actor elsewhere, but this memory +// is not an actor, and the GC must not treat it as one, whatever constant the +// struct's first field points to: a primitive instance or a string literal +// can hold bytes that read as an actor descriptor. Whether those bytes read as +// one depends on where the program is loaded, so a run can pass even when the +// lookup is wrong. +use @ponyint_pool_alloc_size[NullablePointer[S]](size: USize) +use @memset[Pointer[None]](p: NullablePointer[S] tag, c: I32, n: USize) + +primitive P1 +primitive P2 +primitive P3 +primitive P4 + +class D + let n: U64 + + new create(n': U64) => + n = n' + +struct S + var first: Any val = None + var d: D = D(1) + + new create() => + None + +actor Holder + embed s: S = S + + be ping() => + None + +actor Main + let _env: Env + let _blocks: Array[NullablePointer[S]] = Array[NullablePointer[S]] + let _h: Holder = Holder + var _i: USize = 0 + var _last: D = D(0) + + new create(env: Env) => + _env = env + let firsts: Array[Any val] = [P1; P2; P3; P4; "a"; "bc"; "literal"; None] + for first in firsts.values() do + let np = @ponyint_pool_alloc_size(USize(64)) + @memset(np, 0, 64) + try + np()?.first = first + np()?.d = D(42) + _blocks.push(np) + end + end + churn() + + be churn() => + var k: USize = 0 + while k < 1000 do + _last = D(k.u64()) + k = k + 1 + end + for np in _blocks.values() do + try + if np()?.d.n != 42 then _env.exitcode(1) end + else + _env.exitcode(1) + end + end + _i = _i + 1 + if _i < 50 then churn() end diff --git a/test/full-program-tests/embed-gc-remote-struct-and-field/main.pony b/test/full-program-tests/embed-gc-remote-struct-and-field/main.pony new file mode 100644 index 00000000000..000a89cf5ca --- /dev/null +++ b/test/full-program-tests/embed-gc-remote-struct-and-field/main.pony @@ -0,0 +1,60 @@ +// An actor receives a struct iso and keeps both the struct and its first +// embedded field, field first. Its collections must trace the struct's other +// field, which another actor owns. +class C + var x: U64 = 7 + +class D + let n: U64 + new create(n': U64) => n = n' + +struct S + embed c: C = C + var d: D + new create(d': D iso) => d = consume d' + +actor Receiver + var _c: C ref + var _s: S ref + var _last: D = D(0) + var _bad: U64 = 0 + let _env: Env + + new create(env: Env) => + _env = env + _s = S(recover D(0) end) + _c = _s.c + + be take(s: S iso) => + let s': S ref = consume s + _s = s' + _c = s'.c + + be churn(i: U64) => + var k: USize = 0 + while k < 2000 do + _last = D(i) + k = k + 1 + end + if _s.d.n != 0xDEADBEEF then _bad = _bad + 1 end + if i < 200 then churn(i + 1) elseif _bad != 0 then _env.exitcode(1) end + +actor Sender + var _last: D = D(0) + new create(r: Receiver) => + r.take(recover S(recover D(0xDEADBEEF) end) end) + // Same sender, so take arrives before churn. + r.churn(0) + + be churn(i: U64) => + var k: USize = 0 + while k < 2000 do + _last = D(i) + k = k + 1 + end + if i < 200 then churn(i + 1) end + +actor Main + new create(env: Env) => + let r = Receiver(env) + Sender(r).churn(0) diff --git a/test/full-program-tests/embed-gc-routed-tag-in-boxed-tuple/main.pony b/test/full-program-tests/embed-gc-routed-tag-in-boxed-tuple/main.pony new file mode 100644 index 00000000000..5dfbc38b3cc --- /dev/null +++ b/test/full-program-tests/embed-gc-routed-tag-in-boxed-tuple/main.pony @@ -0,0 +1,37 @@ +// Main sends a tag reference to C inside a tuple, in a union that holds the +// tuple boxed. C is embedded at the start of S, so it can share S's address. +// The trace of the tuple's element falls back to the whole union, which must +// still be traced as a type that can share an address. A wrong trace trips the +// pony_assert in pony_traceunknown (trace.c). +class C + var x: U64 = 1 + + new create() => + None + +class D + var y: U64 = 2 + + new create() => + None + +struct S + embed c: C = C + var d: U64 = 3 + + new create() => + None + +actor Receiver + be take(v: (None | (U64, (C tag | D tag)))) => + match v + | (let n: U64, _) => None + end + +actor Main + new create(env: Env) => + let s = S + env.out.print(s.d.string()) + let r = Receiver + let c: C tag = C + r.take((U64(7), c)) diff --git a/test/full-program-tests/embed-gc-struct-field-first-mark/main.pony b/test/full-program-tests/embed-gc-struct-field-first-mark/main.pony new file mode 100644 index 00000000000..728e0553344 --- /dev/null +++ b/test/full-program-tests/embed-gc-struct-field-first-mark/main.pony @@ -0,0 +1,36 @@ +// A struct's first embedded field shares the struct's address. Main declares +// the field before the struct, so its collection reaches the address as the +// field first. The struct's other field must still be traced. +class C + let x: U64 = 7 + +class D + let n: U64 + new create(n': U64) => n = n' + +struct S + embed c: C = C + let d: D + new create(d': D) => d = d' + +actor Main + let _c: C + let _s: S + var _last: D = D(0) + var _bad: U64 = 0 + let _env: Env + + new create(env: Env) => + _env = env + _s = S(D(0xDEADBEEF)) + _c = _s.c + churn(0) + + be churn(i: U64) => + var k: USize = 0 + while k < 2000 do + _last = D(i) + k = k + 1 + end + if _s.d.n != 0xDEADBEEF then _bad = _bad + 1 end + if i < 200 then churn(i + 1) elseif _bad != 0 then _env.exitcode(1) end diff --git a/test/full-program-tests/embed-gc-struct-field-first-message/main.pony b/test/full-program-tests/embed-gc-struct-field-first-message/main.pony new file mode 100644 index 00000000000..15eb4db40d2 --- /dev/null +++ b/test/full-program-tests/embed-gc-struct-field-first-message/main.pony @@ -0,0 +1,54 @@ +// A struct's first embedded field and the struct travel in one message, field +// first. Both the sender and the receiver must count and trace the struct's +// other field. +class C + let x: U64 = 7 + +class D + let n: U64 + new create(n': U64) => n = n' + +struct S + embed c: C = C + let d: D + new create(d': D iso) => d = consume d' + +actor Receiver + var _c: C val + var _s: S val + let _env: Env + var _bad: U64 = 0 + new create(env: Env) => + _env = env + _s = recover S(recover D(0xDEADBEEF) end) end + _c = _s.c + + be take(c: C val, s: S val) => + _c = c + _s = s + + be check(i: U64) => + if _s.d.n != 0xDEADBEEF then _bad = _bad + 1 end + if (i == 200) and (_bad != 0) then _env.exitcode(1) end + +actor Sender + let _r: Receiver + var _last: D = D(0) + new create(r: Receiver) => + _r = r + let s: S val = recover S(recover D(0xDEADBEEF) end) end + _r.take(s.c, s) + + be churn(i: U64) => + var k: USize = 0 + while k < 2000 do + _last = D(i) + k = k + 1 + end + _r.check(i) + if i < 200 then churn(i + 1) end + +actor Main + new create(env: Env) => + let r = Receiver(env) + Sender(r).churn(0) diff --git a/test/full-program-tests/embed-gc-struct-field-first-through-interface/main.pony b/test/full-program-tests/embed-gc-struct-field-first-through-interface/main.pony new file mode 100644 index 00000000000..98dc0320e96 --- /dev/null +++ b/test/full-program-tests/embed-gc-struct-field-first-through-interface/main.pony @@ -0,0 +1,49 @@ +// A struct's first embedded field shares the struct's address. Main holds the +// field through an interface, declared before the struct, so its collection +// reaches the address first by a trace that reads the field's descriptor. The +// struct's other field must still be traced. +interface I + fun x(): U64 + +class C + fun x(): U64 => + 7 + +class D + let n: U64 + + new create(n': U64) => + n = n' + +struct S + embed c: C = C + let d: D + + new create(d': D) => + d = d' + +actor Main + let _c: I + let _s: S + var _last: D = D(0) + var _bad: U64 = 0 + let _env: Env + + new create(env: Env) => + _env = env + _s = S(D(0xDEADBEEF)) + _c = _s.c + churn(0) + + be churn(i: U64) => + var k: USize = 0 + while k < 2000 do + _last = D(i) + k = k + 1 + end + if _s.d.n != 0xDEADBEEF then _bad = _bad + 1 end + if i < 200 then + churn(i + 1) + elseif _bad != 0 then + _env.exitcode(1) + end diff --git a/test/full-program-tests/embed-gc-struct-field-first-through-nested-union/main.pony b/test/full-program-tests/embed-gc-struct-field-first-through-nested-union/main.pony new file mode 100644 index 00000000000..bd9ec288975 --- /dev/null +++ b/test/full-program-tests/embed-gc-struct-field-first-through-nested-union/main.pony @@ -0,0 +1,45 @@ +// Main holds a struct's first embedded field through a union that also holds +// an intersection. The trace checks the value against each type in the union +// in turn; a value that matches none of the intersection's types must still be +// traced as a type that can share the struct's address. A wrong trace trips the +// pony_assert in pony_traceunknown (trace.c). +struct S + embed c: C = C + var x: U8 = 0 + + new create() => + None + +class C + var v: U64 = 0 + + new create() => + None + +interface I1 + fun i1(): U8 + +interface I2 + fun i2(): U8 + +class val K is (I1 & I2) + fun i1(): U8 => + 1 + + fun i2(): U8 => + 2 + +actor Main + var _f: (C tag | (I1 val & I2 val)) + var _s: S + var _n: U32 = 0 + + new create(env: Env) => + _s = S + _f = _s.c + tick() + + be tick() => + _n = _n + 1 + let junk = Array[U8].init(0, 4096) + if _n < 20 then tick() end diff --git a/test/full-program-tests/embed-gc-struct-field-separate-messages/main.pony b/test/full-program-tests/embed-gc-struct-field-separate-messages/main.pony new file mode 100644 index 00000000000..887874a3398 --- /dev/null +++ b/test/full-program-tests/embed-gc-struct-field-separate-messages/main.pony @@ -0,0 +1,56 @@ +// A struct's first embedded field and the struct travel in separate messages, +// field first. The receiver's collections must trace the struct's other field. +class C + let x: U64 = 7 + +class D + let n: U64 + new create(n': U64) => n = n' + +struct S + embed c: C = C + let d: D + new create(d': D iso) => d = consume d' + +actor Receiver + var _c: C val + var _s: S val + let _env: Env + var _bad: U64 = 0 + new create(env: Env) => + _env = env + _s = recover S(recover D(0xDEADBEEF) end) end + _c = _s.c + + be take_c(c: C val) => + _c = c + + be take_s(s: S val) => + _s = s + + be check(i: U64) => + if _s.d.n != 0xDEADBEEF then _bad = _bad + 1 end + if (i == 200) and (_bad != 0) then _env.exitcode(1) end + +actor Sender + let _r: Receiver + var _last: D = D(0) + new create(r: Receiver) => + _r = r + let s: S val = recover S(recover D(0xDEADBEEF) end) end + _r.take_c(s.c) + _r.take_s(s) + + be churn(i: U64) => + var k: USize = 0 + while k < 2000 do + _last = D(i) + k = k + 1 + end + _r.check(i) + if i < 200 then churn(i + 1) end + +actor Main + new create(env: Env) => + let r = Receiver(env) + Sender(r).churn(0) diff --git a/test/full-program-tests/embed-gc-struct-fields-without-the-struct/main.pony b/test/full-program-tests/embed-gc-struct-fields-without-the-struct/main.pony new file mode 100644 index 00000000000..35954915c65 --- /dev/null +++ b/test/full-program-tests/embed-gc-struct-fields-without-the-struct/main.pony @@ -0,0 +1,56 @@ +// Main keeps a struct's first two embedded fields but not the struct. The +// first field reaches the struct's address first, and the second field's +// references must still survive Main's collections. One struct has two fields +// of the same type, the other two fields of different types. +class D + let n: U64 + new create(n': U64) => n = n' + +class C + var d: D + new create(n: U64) => d = D(n) + +class E + var x: U64 = 1 + +class F + var d: D = D(0xDEADBEEF) + +struct Same + embed a: C = C(1) + embed b: C = C(0xDEADBEEF) + new create() => None + +struct Mixed + embed e: E = E + embed f: F = F + new create() => None + +actor Main + let _a: C + let _b: C + let _e: E + let _f: F + var _last: D = D(0) + var _bad: U64 = 0 + let _env: Env + + new create(env: Env) => + _env = env + let same = Same + _a = same.a + _b = same.b + let mixed = Mixed + _e = mixed.e + _f = mixed.f + churn(0) + + be churn(i: U64) => + var k: USize = 0 + while k < 2000 do + _last = D(i) + k = k + 1 + end + if _b.d.n != 0xDEADBEEF then _bad = _bad + 1 end + if _f.d.n != 0xDEADBEEF then _bad = _bad + 1 end + if i < 200 then churn(i + 1) elseif _bad != 0 then _env.exitcode(1) end diff --git a/test/full-program-tests/embed-gc-struct-first-field-only/main.pony b/test/full-program-tests/embed-gc-struct-first-field-only/main.pony new file mode 100644 index 00000000000..06553b7fc42 --- /dev/null +++ b/test/full-program-tests/embed-gc-struct-first-field-only/main.pony @@ -0,0 +1,34 @@ +// Main keeps only a struct's first embedded field; that field references D. +// D must survive Main's collections. +class D + let n: U64 + new create(n': U64) => n = n' + +class C + var d: D = D(0xDEADBEEF) + +struct S + embed c: C = C + var x: U64 = 0 + new create() => None + +actor Main + let _c: C + var _last: D = D(0) + var _bad: U64 = 0 + let _env: Env + + new create(env: Env) => + _env = env + let s = S + _c = s.c + churn(0) + + be churn(i: U64) => + var k: USize = 0 + while k < 2000 do + _last = D(i) + k = k + 1 + end + if _c.d.n != 0xDEADBEEF then _bad = _bad + 1 end + if i < 200 then churn(i + 1) elseif _bad != 0 then _env.exitcode(1) end diff --git a/test/full-program-tests/embed-gc-visit-set-keyed-by-type/main.pony b/test/full-program-tests/embed-gc-visit-set-keyed-by-type/main.pony new file mode 100644 index 00000000000..2368bb3a1ce --- /dev/null +++ b/test/full-program-tests/embed-gc-visit-set-keyed-by-type/main.pony @@ -0,0 +1,53 @@ +// T starts with S, which starts with C, so all three share an address. Main +// keeps C twice and S, but not T, in that order. S's own field must survive. +class D + let n: U64 + + new create(n': U64) => + n = n' + +class C + var e: D = D(1) + +struct S + embed c: C = C + var d: D = D(0xDEADBEEF) + + new create() => + None + +struct T + embed s: S = S + var y: U64 = 0 + + new create() => + None + +actor Main + let _c1: C + let _c2: C + let _s: S + var _last: D = D(0) + var _bad: U64 = 0 + let _env: Env + + new create(env: Env) => + _env = env + let t = T + _c1 = t.s.c + _c2 = t.s.c + _s = t.s + churn(0) + + be churn(i: U64) => + var k: USize = 0 + while k < 2000 do + _last = D(i) + k = k + 1 + end + if _s.d.n != 0xDEADBEEF then _bad = _bad + 1 end + if i < 200 then + churn(i + 1) + elseif _bad != 0 then + _env.exitcode(1) + end diff --git a/test/full-program-tests/gc-pointer-at-struct-start-send/main.pony b/test/full-program-tests/gc-pointer-at-struct-start-send/main.pony new file mode 100644 index 00000000000..3d8559d9fc0 --- /dev/null +++ b/test/full-program-tests/gc-pointer-at-struct-start-send/main.pony @@ -0,0 +1,77 @@ +// Main sends a Receiver a holder whose Pointer to the start of a struct comes +// before the struct itself, so the send visits the Pointer first. That visit +// must not stop the struct's own trace, or the struct's field isn't counted +// for the Receiver and Main frees it while the Receiver still holds it. +use @memmove[Pointer[U8]](dst: S tag, src: S tag, n: USize) + +class D + let n: U64 + + new create(n': U64) => + n = n' + +struct S + var d: D = D(777777) + + new create() => + None + +class Holder + var p: Pointer[U8] + var s: S + + new create() => + let s' = S + p = @memmove(s', s', 0) + s = s' + +actor Receiver + let _env: Env + var _h: Holder = Holder + var _stop: Bool = false + + new create(env: Env) => + _env = env + + be take(h: Holder iso) => + _h = consume h + check() + + be stop() => + _stop = true + + be check() => + var k: USize = 0 + while k < 200 do + D(k.u64()) + k = k + 1 + end + if _h.s.d.n != 777777 then + _env.exitcode(1) + return + end + if not _stop then check() end + +actor Main + var _last: D = D(0) + var _i: USize = 0 + let _r: Receiver + + new create(env: Env) => + _r = Receiver(env) + let h: Holder iso = recover iso Holder end + _r.take(consume h) + churn() + + fun @runtime_override_defaults(rto: RuntimeOptions) => + rto.ponygcinitial = 0 + rto.ponygcfactor = 1.0 + + be churn() => + var k: USize = 0 + while k < 10000 do + _last = D(k.u64()) + k = k + 1 + end + _i = _i + 1 + if _i < 300 then churn() else _r.stop() end diff --git a/test/full-program-tests/gc-pointer-at-struct-start/main.pony b/test/full-program-tests/gc-pointer-at-struct-start/main.pony new file mode 100644 index 00000000000..b35267be404 --- /dev/null +++ b/test/full-program-tests/gc-pointer-at-struct-start/main.pony @@ -0,0 +1,53 @@ +// A class holds a Pointer to the start of a struct before it holds the struct +// itself, so a mark visits the Pointer first. A Pointer has no trace function; +// its visit must not mark the struct's allocation as traced, or the struct's +// field is freed while it is still reachable. +use @memmove[Pointer[U8]](dst: S tag, src: S tag, n: USize) + +class D + let n: U64 + + new create(n': U64) => + n = n' + +struct S + var d: D = D(777777) + + new create() => + None + +class Holder + var p: Pointer[U8] + var s: S + + new create() => + let s' = S + p = @memmove(s', s', 0) + s = s' + +actor Main + let _env: Env + let _h: Holder = Holder + var _i: USize = 0 + var _last: D = D(0) + + new create(env: Env) => + _env = env + churn() + + fun @runtime_override_defaults(rto: RuntimeOptions) => + rto.ponygcinitial = 0 + rto.ponygcfactor = 1.0 + + be churn() => + var k: USize = 0 + while k < 10000 do + _last = D(k.u64()) + k = k + 1 + end + if _h.s.d.n != 777777 then + _env.exitcode(1) + return + end + _i = _i + 1 + if _i < 50 then churn() end diff --git a/test/libponyc/CMakeLists.txt b/test/libponyc/CMakeLists.txt index ad5ffdf3215..108f2d73d04 100644 --- a/test/libponyc/CMakeLists.txt +++ b/test/libponyc/CMakeLists.txt @@ -13,6 +13,8 @@ add_executable(libponyc.tests cap_safety.cc chain.cc codegen.cc + codegen_sections.cc + codegen_embed.cc codegen_ffi.cc codegen_debug_info.cc codegen_match_narrow.cc diff --git a/test/libponyc/codegen_embed.cc b/test/libponyc/codegen_embed.cc new file mode 100644 index 00000000000..fcd1f43379d --- /dev/null +++ b/test/libponyc/codegen_embed.cc @@ -0,0 +1,806 @@ +#include +#include +#include +#include +#include +#include "../../src/libponyrt/gc/embedflags.h" +#include "util.h" +#include +#include "llvm_config_begin.h" +#include +#include +#include +#include "llvm_config_end.h" + +#define TEST_COMPILE(src) DO(test_compile(src, "ir")) + +// A trace that can reach a type whose objects can share an address with an +// object of another type goes to the runtime's routed entry points. + +class CodegenEmbedTest : public PassTest +{ +protected: + // Calls to the named function, in functions whose name starts with prefix. + // With mutability at 0 or more, only calls whose last argument is that + // constant. + size_t calls_to(const char* name, const char* prefix = "", + int mutability = -1) + { + auto module = llvm::unwrap(compile->module); + size_t count = 0; + + for(auto& function : *module) + { + if(!function.getName().starts_with(prefix)) + continue; + + for(auto& block : function) + { + for(auto& inst : block) + { + auto call = llvm::dyn_cast(&inst); + if(call == nullptr) + continue; + + auto callee = call->getCalledFunction(); + if((callee == nullptr) || (callee->getName() != name)) + continue; + + if(mutability >= 0) + { + auto last = llvm::dyn_cast( + call->getArgOperand(call->arg_size() - 1)); + if((last == nullptr) || (last->getSExtValue() != mutability)) + continue; + } + + count++; + } + } + } + + return count; + } + + uint8_t flags_of(const char* type_name) + { + reach_type_t* t = reach_type_name(compile->reach, type_name, &opt); + if(t == NULL) + { + ADD_FAILURE() << "no reachable type " << type_name; + return 0; + } + + return ((compile_type_t*)t->c_type)->embed_flags; + } +}; + +TEST_F(CodegenEmbedTest, ProgramWithoutEmbedUsesPlainTraces) +{ + const char* src = + "interface Thing\n" + " fun value(): U64\n" + + "class A is Thing\n" + " let s: String = \"a\"\n" + " fun value(): U64 => 1\n" + + "actor Keeper\n" + " var _t: (Thing | None) = None\n" + " be take(t: Thing iso) => _t = consume t\n" + + "actor Main\n" + " new create(env: Env) =>\n" + " Keeper.take(recover A end)"; + + TEST_COMPILE(src); + + ASSERT_GT(calls_to("pony_traceknown") + calls_to("pony_traceunknown"), 0u); + ASSERT_EQ(0u, calls_to("pony_traceknown_routed")); + ASSERT_EQ(0u, calls_to("pony_traceunknown_routed")); +} + +// A union of a tuple and a routed class (embedded at a struct's start): the +// trace that checks for a boxed tuple can also receive a C, so it must be +// routed. +TEST_F(CodegenEmbedTest, UnionWithTupleAndEmbeddedTypeIsRouted) +{ + const char* src = + "class C\n" + " var x: U64 = 7\n" + + "struct A\n" + " embed c: C = C\n" + " new create() => None\n" + + "actor Keeper\n" + " var _v: ((String, String) | C val) = (\"a\", \"b\")\n" + " be take(v: ((String, String) | C val)) => _v = v\n" + + "actor Main\n" + " new create(env: Env) =>\n" + " let a: A val = recover A end\n" + " Keeper.take(a.c)"; + + TEST_COMPILE(src); + + // Keeper traces the union when it receives it and when it collects. + ASSERT_GT(calls_to("pony_traceunknown_routed", "Keeper_"), 0u); + ASSERT_EQ(0u, calls_to("pony_traceunknown", "Keeper_")); +} + +// A union that names a type alias, where no type is routed: the alias is +// unfolded, so the union's trace takes the plain path. +TEST_F(CodegenEmbedTest, UnionWithAnAliasOfPlainTypesIsNotRouted) +{ + const char* src = + "class C\n" + " var x: U64 = 7\n" + + "type Plain is (String | C val)\n" + + "actor Keeper\n" + " var _v: (Plain | Env) = \"a\"\n" + " be take(v: (Plain | Env)) => _v = v\n" + + "actor Main\n" + " new create(env: Env) =>\n" + " Keeper.take(recover val C end)"; + + TEST_COMPILE(src); + + ASSERT_GT(calls_to("pony_traceunknown", "Keeper_"), 0u); + ASSERT_EQ(0u, calls_to("pony_traceunknown_routed", "Keeper_")); +} + +// A union that names an alias of an alias whose members include a routed +// class: the union's trace is routed. +TEST_F(CodegenEmbedTest, UnionWithAnAliasOfARoutedTypeIsRouted) +{ + const char* src = + "class C\n" + " var x: U64 = 7\n" + + "struct A\n" + " embed c: C = C\n" + " new create() => None\n" + + "type Inner is (String | C val)\n" + "type Outer is (Inner | Env)\n" + + "actor Keeper\n" + " var _v: (Outer | None) = None\n" + " be take(v: (Outer | None)) => _v = v\n" + + "actor Main\n" + " new create(env: Env) =>\n" + " let a: A val = recover A end\n" + " Keeper.take(a.c)"; + + TEST_COMPILE(src); + + ASSERT_GT(calls_to("pony_traceunknown_routed", "Keeper_"), 0u); + ASSERT_EQ(0u, calls_to("pony_traceunknown", "Keeper_")); +} + +// A boxed tuple whose element can be a routed class: the element's trace +// falls back to the whole union, so it is routed. +TEST_F(CodegenEmbedTest, BoxedTupleWithARoutedElementIsRouted) +{ + const char* src = + "class C\n" + " var x: U64 = 1\n" + + "class D\n" + " var y: U64 = 2\n" + + "struct S\n" + " embed c: C = C\n" + " new create() => None\n" + + "actor Receiver\n" + " be take(v: (None | (U64, (C tag | D tag)))) => None\n" + + "actor Main\n" + " new create(env: Env) =>\n" + " let s = S\n" + " let c: C tag = C\n" + " Receiver.take((U64(7), c))"; + + TEST_COMPILE(src); + + ASSERT_GT(calls_to("pony_traceunknown_routed", "Receiver_"), 0u); + ASSERT_EQ(0u, calls_to("pony_traceunknown", "Receiver_")); +} + +// A boxed tuple of types that aren't routed takes the plain trace. +TEST_F(CodegenEmbedTest, BoxedTupleOfPlainTypesIsNotRouted) +{ + const char* src = + "class C\n" + " var x: U64 = 1\n" + + "class D\n" + " var y: U64 = 2\n" + + "struct S\n" + " embed c: C = C\n" + " new create() => None\n" + + "actor Receiver\n" + " be take(v: (None | (U64, D tag))) => None\n" + + "actor Main\n" + " new create(env: Env) =>\n" + " let s = S\n" + " let d: D tag = D\n" + " Receiver.take((U64(7), d))"; + + TEST_COMPILE(src); + + ASSERT_GT(calls_to("pony_traceunknown", "Receiver_"), 0u); + ASSERT_EQ(0u, calls_to("pony_traceunknown_routed", "Receiver_")); +} + +// A Pointer can point at the start of an object of another type and has no +// trace function, so a ref or a val Pointer is traced as opaque and with no +// type. +TEST_F(CodegenEmbedTest, KnownTraceOfAPointerHasNoType) +{ + const char* src = + "class C\n" + " var p: Pointer[U8] = Pointer[U8]\n" + " let q: Pointer[U8] val = recover val Pointer[U8] end\n" + + "actor Keeper\n" + " be take(c: C iso) => None\n" + + "actor Main\n" + " new create(env: Env) =>\n" + " Keeper.take(recover C end)"; + + TEST_COMPILE(src); + + ASSERT_GE(calls_to("pony_trace", "C_"), 2u); + ASSERT_EQ(0u, calls_to("pony_traceknown", "C_")); + ASSERT_EQ(0u, calls_to("pony_traceknown_routed", "C_")); + ASSERT_EQ(0u, calls_to("pony_traceunknown", "C_")); + ASSERT_EQ(0u, calls_to("pony_traceunknown_routed", "C_")); +} + +// A union that holds an intersection: a value that matches none of the +// intersection's types is traced by the fallback, which must choose the routed +// call by the whole union, since the value can be the struct's first field. +TEST_F(CodegenEmbedTest, NestedUnionFallbackIsRouted) +{ + const char* src = + "class C\n" + " var v: U64 = 0\n" + + "struct S\n" + " embed c: C = C\n" + " new create() => None\n" + + "interface I1\n" + " fun i1(): U8\n" + + "interface I2\n" + " fun i2(): U8\n" + + "actor Main\n" + " var _f: (C tag | (I1 val & I2 val))\n" + " var _s: S\n" + " new create(env: Env) =>\n" + " _s = S\n" + " _f = _s.c"; + + TEST_COMPILE(src); + + // The fallback traces opaque. A value that matched I1 or I2 is traced plain, + // since no type that can share an address provides them. + ASSERT_GT(calls_to("pony_traceunknown_routed", "Main_", PONY_TRACE_OPAQUE), + 0u); + ASSERT_EQ(0u, calls_to("pony_traceunknown", "Main_", PONY_TRACE_OPAQUE)); +} + +// A field with no size at a struct's start sits at offset 0 with the field +// after it; the one with a non-zero size starts the struct. +TEST_F(CodegenEmbedTest, ZeroSizeFieldBeforeTheFirstRealField) +{ + const char* src = + "struct Z\n" + " new create() => None\n" + + "class T\n" + " var x: U64 = 0\n" + + "struct S\n" + " embed z: Z = Z\n" + " embed t: T = T\n" + " var f: U64 = 0\n" + " new create() => None\n" + + "actor Main\n" + " var _s: S = S\n" + " new create(env: Env) => None"; + + TEST_COMPILE(src); + + reach_type_t* s = reach_type_name(compile->reach, "S", &opt); + reach_type_t* t = reach_type_name(compile->reach, "T", &opt); + ASSERT_NE(nullptr, s); + ASSERT_NE(nullptr, t); + ASSERT_EQ(t, gentype_first_embed(compile, s)); + + ASSERT_NE(0, flags_of("S") & PONY_EMBED_ROUTED); +} + +// Each reification is its own type: embedding one at a struct's start doesn't +// route another. +TEST_F(CodegenEmbedTest, OnlyTheEmbeddedReificationIsRouted) +{ + const char* src = + "struct H\n" + " embed a: Array[U8] = Array[U8]\n" + " new create() => None\n" + + "actor Main\n" + " var _h: H = H\n" + " var _b: Array[U16] = Array[U16]\n" + " new create(env: Env) => None"; + + TEST_COMPILE(src); + + ASSERT_NE(0, flags_of("Array_U8_val") & PONY_EMBED_ROUTED); + ASSERT_EQ(0, flags_of("Array_U16_val") & PONY_EMBED_ROUTED); +} + +// A type embedded in an actor can be found inside one, and the actor must be +// findable from the address of that field. +TEST_F(CodegenEmbedTest, EmbeddedInAnActor) +{ + const char* src = + "class C\n" + " var x: U64 = 0\n" + + "class D\n" + " var y: U64 = 0\n" + + "class H\n" + " embed d: D = D\n" + + "class F\n" + " var z: U64 = 0\n" + + "class E\n" + " embed f: F = F\n" + + "actor Main\n" + " embed c: C = C\n" + " embed e: E = E\n" + " var _h: H = H\n" + " new create(env: Env) => None"; + + TEST_COMPILE(src); + + ASSERT_NE(0, flags_of("C") & PONY_EMBED_IN_ACTOR); + // Embedded in an object that is embedded in an actor. + ASSERT_NE(0, flags_of("F") & PONY_EMBED_IN_ACTOR); + ASSERT_NE(0, flags_of("Main") & PONY_EMBED_ACTOR_LOOKUP); + ASSERT_EQ(0, flags_of("D") & PONY_EMBED_IN_ACTOR); + ASSERT_EQ(0, flags_of("H") & PONY_EMBED_ACTOR_LOOKUP); +} + +// A trace through an interface or trait reaches every class that provides it, +// so it is routed when one of them is embedded at a struct's start. +TEST_F(CodegenEmbedTest, InterfaceAndTraitReachingAnEmbeddedClassAreRouted) +{ + const char* src = + "interface I\n" + " fun i(): U64\n" + + "trait T\n" + " fun t(): U64\n" + + "class C is (I & T)\n" + " var x: U64 = 7\n" + " fun i(): U64 => x\n" + " fun t(): U64 => x\n" + + "struct A\n" + " embed c: C = C\n" + " new create() => None\n" + + "actor Keeper\n" + " var _i: (I val | None) = None\n" + " var _t: (T val | None) = None\n" + " be take_i(i: I val) => _i = i\n" + " be take_t(t: T val) => _t = t\n" + + "actor Main\n" + " new create(env: Env) =>\n" + " let a: A val = recover A end\n" + " let k = Keeper\n" + " k.take_i(a.c)\n" + " k.take_t(a.c)"; + + TEST_COMPILE(src); + + ASSERT_GT(calls_to("pony_traceunknown_routed", "Keeper_"), 0u); + ASSERT_EQ(0u, calls_to("pony_traceunknown", "Keeper_")); +} + +// A struct whose first field with a non-zero size isn't embedded doesn't share +// its address with an embedded object. +TEST_F(CodegenEmbedTest, StructStartingWithAPlainFieldIsNotRouted) +{ + const char* src = + "class C\n" + " var x: U64 = 0\n" + + "struct S\n" + " var a: U64 = 0\n" + " embed c: C = C\n" + " new create() => None\n" + + "actor Main\n" + " var _s: S = S\n" + " new create(env: Env) => None"; + + TEST_COMPILE(src); + + reach_type_t* s = reach_type_name(compile->reach, "S", &opt); + ASSERT_NE(nullptr, s); + ASSERT_EQ(nullptr, gentype_first_embed(compile, s)); + ASSERT_EQ(0, flags_of("S") & PONY_EMBED_ROUTED); +} + +// A struct that starts with an embedded field is allocated with the +// shared-start allocator; a struct that starts with a plain field isn't. +TEST_F(CodegenEmbedTest, StructStartingWithEmbedUsesSharedStartAllocator) +{ + const char* src = + "class E\n" + " var x: U64 = 0\n" + + "struct Shared\n" + " embed e: E = E\n" + " var y: U64 = 0\n" + " new create() => None\n" + + "struct Plain\n" + " var y: U64 = 0\n" + " embed e: E = E\n" + " new create() => None\n" + + "actor Main\n" + " new create(env: Env) =>\n" + " make_shared()\n" + " make_plain()\n" + " fun make_shared(): Shared => Shared\n" + " fun make_plain(): Plain => Plain"; + + TEST_COMPILE(src); + + ASSERT_GT(calls_to("pony_alloc_small_shared_start", "Main_ref_make_shared"), + 0u); + ASSERT_EQ(0u, + calls_to("pony_alloc_small_shared_start", "Main_ref_make_plain")); + ASSERT_GT(calls_to("pony_alloc_small", "Main_ref_make_plain"), 0u); +} + +// A trace of a field whose type is embedded at a struct's start is routed. +TEST_F(CodegenEmbedTest, KnownTraceOfAnEmbeddedTypeIsRouted) +{ + const char* src = + "class C\n" + " var x: U64 = 7\n" + + "struct A\n" + " embed c: C = C\n" + " new create() => None\n" + + "actor Keeper\n" + " var _c: C val = recover C end\n" + " be take(c: C val) => _c = c\n" + + "actor Main\n" + " new create(env: Env) =>\n" + " let a: A val = recover A end\n" + " Keeper.take(a.c)"; + + TEST_COMPILE(src); + + ASSERT_GT(calls_to("pony_traceknown_routed", "Keeper_"), 0u); +} + +// A class that embeds a field with no size shares its address with that field, +// so traces of the class are routed. +TEST_F(CodegenEmbedTest, ClassEmbeddingAFieldWithNoSizeIsRouted) +{ + const char* src = + "struct Z\n" + " new create() => None\n" + + "class D\n" + " embed z: Z = Z\n" + " var x: U64 = 0\n" + + "class P\n" + " var x: U64 = 0\n" + + "actor Main\n" + " var _d: D = D\n" + " var _p: P = P\n" + " new create(env: Env) => None"; + + TEST_COMPILE(src); + + ASSERT_NE(0, flags_of("D") & PONY_EMBED_ROUTED); + ASSERT_EQ(0, flags_of("P") & PONY_EMBED_ROUTED); +} + +// A known trace of an embedded field with no size goes to +// pony_traceknown_routed, which traces it as opaque: such a field has its +// holder's address. +TEST_F(CodegenEmbedTest, KnownTraceOfATypeWithNoSizeIsRouted) +{ + const char* src = + "struct Z\n" + " new create() => None\n" + + "class D\n" + " embed z: Z = Z\n" + " var x: U64 = 0\n" + + "actor Keeper\n" + " var _z: Z val = recover Z end\n" + " be take(z: Z val) => _z = z\n" + + "actor Main\n" + " new create(env: Env) =>\n" + " let d: D val = recover D end\n" + " Keeper.take(d.z)"; + + TEST_COMPILE(src); + + auto module = llvm::unwrap(compile->module); + auto z_desc = module->getNamedGlobal("Z_Desc"); + ASSERT_NE(nullptr, z_desc); + + size_t routed = 0; + size_t plain = 0; + + for(auto& function : *module) + { + for(auto& block : function) + { + for(auto& inst : block) + { + auto call = llvm::dyn_cast(&inst); + if((call == nullptr) || (call->getCalledFunction() == nullptr)) + continue; + + llvm::StringRef callee = call->getCalledFunction()->getName(); + + if(((callee != "pony_traceknown_routed") && + (callee != "pony_traceknown")) || + (call->getArgOperand(2)->stripPointerCasts() != z_desc)) + continue; + + if(callee == "pony_traceknown_routed") + routed++; + else + plain++; + } + } + } + + ASSERT_GT(routed, 0u); + ASSERT_EQ(0u, plain); +} + +// A struct's descriptor records the type at its start in the instance slot +// when that type is an embedded field with a non-zero size, and NULL otherwise. +TEST_F(CodegenEmbedTest, StructDescriptorNamesTheTypeAtItsStart) +{ + const char* src = + "class E\n" + " var x: U64 = 0\n" + + "struct Shared\n" + " embed e: E = E\n" + " var y: U64 = 0\n" + " new create() => None\n" + + "struct Plain\n" + " var y: U64 = 0\n" + " embed e: E = E\n" + " new create() => None\n" + + "actor Main\n" + " new create(env: Env) =>\n" + " let s = Shared\n" + " let p = Plain"; + + TEST_COMPILE(src); + + auto module = llvm::unwrap(compile->module); + auto e_desc = module->getNamedGlobal("E_Desc"); + ASSERT_NE(nullptr, e_desc); + + for(const char* name : {"Shared_Desc", "Plain_Desc"}) + { + SCOPED_TRACE(name); + auto desc = module->getNamedGlobal(name); + ASSERT_NE(nullptr, desc); + ASSERT_TRUE(desc->hasInitializer()); + auto instance = + desc->getInitializer()->getAggregateElement((unsigned)DESC_INSTANCE); + ASSERT_NE(nullptr, instance); + + if(std::string(name) == "Shared_Desc") + EXPECT_EQ(e_desc, instance->stripPointerCasts()); + else + EXPECT_TRUE(instance->isNullValue()); + } +} + +// The type of a struct's first embedded field with a non-zero size is flagged +// as possibly at the start of another type's allocation, through every level +// of nesting; a field embedded later in a struct isn't. +TEST_F(CodegenEmbedTest, TypeEmbeddedAtAStructsStartIsFlagged) +{ + const char* src = + "class C\n" + " var x: U64 = 0\n" + + "class L\n" + " var x: U64 = 0\n" + + "struct S\n" + " embed c: C = C\n" + " embed l: L = L\n" + " new create() => None\n" + + "struct T\n" + " embed s: S = S\n" + " var y: U64 = 0\n" + " new create() => None\n" + + "class H\n" + " var t: T = T\n" + + "actor Main\n" + " new create(env: Env) =>\n" + " let h = H"; + + TEST_COMPILE(src); + + ASSERT_NE(0, flags_of("C") & PONY_EMBED_AT_START); + ASSERT_NE(0, flags_of("S") & PONY_EMBED_AT_START); + ASSERT_EQ(0, flags_of("L") & PONY_EMBED_AT_START); + ASSERT_EQ(0, flags_of("T") & PONY_EMBED_AT_START); + + // A struct that starts with an embedded field shares its address with that + // field, so it is routed too, at every level of the chain. + ASSERT_NE(0, flags_of("C") & PONY_EMBED_ROUTED); + ASSERT_NE(0, flags_of("S") & PONY_EMBED_ROUTED); + ASSERT_NE(0, flags_of("T") & PONY_EMBED_ROUTED); + ASSERT_EQ(0, flags_of("L") & PONY_EMBED_ROUTED); + + // A field of the outer struct's type is traced through the routed call. + ASSERT_GT(calls_to("pony_traceknown_routed", "H_"), 0u); + ASSERT_EQ(0u, calls_to("pony_traceknown", "H_")); +} + +// A struct that starts with an embedded field and is larger than the largest +// small allocation is allocated with the large shared-start allocator. +TEST_F(CodegenEmbedTest, LargeStructStartingWithEmbedUsesSharedStartAllocator) +{ + const char* src = + "class E\n" + " var x: U64 = 0\n" + + "struct Pad\n" + " var p0: U64 = 0\n var p1: U64 = 0\n var p2: U64 = 0\n" + " var p3: U64 = 0\n var p4: U64 = 0\n var p5: U64 = 0\n" + " var p6: U64 = 0\n var p7: U64 = 0\n" + " new create() => None\n" + + "struct Shared\n" + " embed e: E = E\n" + " embed a: Pad = Pad\n embed b: Pad = Pad\n embed c: Pad = Pad\n" + " embed d: Pad = Pad\n embed f: Pad = Pad\n embed g: Pad = Pad\n" + " embed h: Pad = Pad\n embed i: Pad = Pad\n" + " new create() => None\n" + + "actor Main\n" + " new create(env: Env) =>\n" + " make_shared()\n" + " fun make_shared(): Shared => Shared"; + + TEST_COMPILE(src); + + ASSERT_GT(calls_to("pony_alloc_large_shared_start", "Main_ref_make_shared"), + 0u); + ASSERT_EQ(0u, + calls_to("pony_alloc_small_shared_start", "Main_ref_make_shared")); +} + +// The descriptor type the compiler emits lays its fields out as the runtime's +// _pony_type_t does, at the indices named by DESC_*. +TEST_F(CodegenEmbedTest, DescriptorLayoutMatchesTheRuntime) +{ + const char* src = + "actor Main\n" + " new create(env: Env) => None"; + + TEST_COMPILE(src); + + LLVMTypeRef desc = compile->descriptor_type; + LLVMTargetDataRef data = compile->target_data; + auto offset = [&](unsigned index) + { + return (size_t)LLVMOffsetOfElement(data, desc, index); + }; + + EXPECT_EQ(offsetof(_pony_type_t, id), offset(DESC_ID)); + EXPECT_EQ(offsetof(_pony_type_t, size), offset(DESC_SIZE)); + EXPECT_EQ(offsetof(_pony_type_t, field_count), offset(DESC_FIELD_COUNT)); + EXPECT_EQ(offsetof(_pony_type_t, field_offset), offset(DESC_FIELD_OFFSET)); + EXPECT_EQ(offsetof(_pony_type_t, instance), offset(DESC_INSTANCE)); + EXPECT_EQ(offsetof(_pony_type_t, name), offset(DESC_NAME)); + EXPECT_EQ(offsetof(_pony_type_t, get_behavior_name), + offset(DESC_GET_BEHAVIOR_NAME)); + EXPECT_EQ(offsetof(_pony_type_t, trace), offset(DESC_TRACE)); + EXPECT_EQ(offsetof(_pony_type_t, dispatch), offset(DESC_DISPATCH)); + EXPECT_EQ(offsetof(_pony_type_t, final), offset(DESC_FINALISE)); + EXPECT_EQ(offsetof(_pony_type_t, event_notify), offset(DESC_EVENT_NOTIFY)); + EXPECT_EQ(offsetof(_pony_type_t, might_reference_actor), + offset(DESC_MIGHT_REFERENCE_ACTOR)); + EXPECT_EQ(offsetof(_pony_type_t, embed_flags), offset(DESC_EMBED_FLAGS)); + EXPECT_EQ(offsetof(_pony_type_t, traits), offset(DESC_TRAITS)); + EXPECT_EQ(offsetof(_pony_type_t, fields), offset(DESC_FIELDS)); + EXPECT_EQ(offsetof(_pony_type_t, vtable), offset(DESC_VTABLE)); +} + +// A type embedded only where it shares no address with another object, inside +// a class or an actor or after a struct's first field, takes the plain trace. +TEST_F(CodegenEmbedTest, TypeEmbeddedWithoutASharedAddressIsNotRouted) +{ + const char* src = + "class C\n" + " var x: U64 = 0\n" + + "class D\n" + " var x: U64 = 0\n" + + "class E\n" + " var x: U64 = 0\n" + + "class F\n" + " var x: U64 = 0\n" + + "class H\n" + " embed c: C = C\n" + + "struct S\n" + " embed f: F = F\n" + " embed e: E = E\n" + " new create() => None\n" + + "actor Main\n" + " embed d: D = D\n" + " var _h: H = H\n" + " var _s: S = S\n" + " new create(env: Env) => None"; + + TEST_COMPILE(src); + + ASSERT_EQ(0, flags_of("C") & PONY_EMBED_ROUTED); + ASSERT_EQ(0, flags_of("D") & PONY_EMBED_ROUTED); + ASSERT_EQ(0, flags_of("E") & PONY_EMBED_ROUTED); + ASSERT_NE(0, flags_of("F") & PONY_EMBED_ROUTED); + ASSERT_NE(0, flags_of("D") & PONY_EMBED_IN_ACTOR); +} diff --git a/test/libponyc/codegen_optimisation.cc b/test/libponyc/codegen_optimisation.cc index 6d6819b3d9a..d3642382477 100644 --- a/test/libponyc/codegen_optimisation.cc +++ b/test/libponyc/codegen_optimisation.cc @@ -439,6 +439,37 @@ TEST_F(CodegenOptimisationTest, HeapToStackStoreToAlloca) } +TEST_F(CodegenOptimisationTest, HeapToStackStructStartingWithAnEmbeddedField) +{ + // A struct that starts with an embedded field is allocated with + // pony_alloc_small_shared_start, and is promoted like any other allocation. + const char* src = + "class C\n" + " var x: U64 = 1\n" + + "struct S\n" + " embed c: C = C\n" + " var y: U64 = 2\n" + " new create() => None\n" + + "actor Main\n" + " new create(env: Env) =>\n" + " let s = S\n" + " let x = s.c.x + s.y"; + + opt.release = true; + + TEST_COMPILE(src); + + size_t before = count_calls_to("pony_alloc_small_shared_start"); + ASSERT_GT(before, 0u); + DO(optimise_with_heap_to_stack()); + size_t after = count_calls_to("pony_alloc_small_shared_start"); + + ASSERT_LT(after, before); +} + + TEST_F(CodegenOptimisationTest, HeapToStackStoreToEscapingNotPromoted) { // An object stored into an actor field escapes — it must stay on the diff --git a/test/libponyc/codegen_sections.cc b/test/libponyc/codegen_sections.cc new file mode 100644 index 00000000000..e65db4ec2cd --- /dev/null +++ b/test/libponyc/codegen_sections.cc @@ -0,0 +1,135 @@ +#include +#include +#include +#include "util.h" +#include +#include "llvm_config_begin.h" +#include +#include +#include +#include "llvm_config_end.h" + +#include + +#define TEST_COMPILE(src) DO(test_compile(src, "ir")) + +// The compiler puts its type descriptors in one section and the other objects +// it emits as constants in another, for each object format. The runtime reads +// where both start and end: it doesn't trace objects in the constant section, +// and it takes a pool block for an actor only if the block's first word points +// into the descriptor section. + +namespace +{ +const char* section_for(const char* triple) +{ + std::string copy = triple; + return target_constant_section(©[0]); +} +} + +TEST(TargetSections, OneConstantSectionPerObjectFormat) +{ + EXPECT_STREQ(".data.rel.ro.pony-const", + section_for("x86_64-unknown-linux-gnu")); + EXPECT_STREQ(".data.rel.ro.pony-const", + section_for("aarch64-unknown-freebsd")); + EXPECT_STREQ("__DATA_CONST,__pony_const", section_for("arm64-apple-macosx")); + EXPECT_STREQ(".ponyc$m", section_for("x86_64-pc-windows-msvc")); + EXPECT_EQ(nullptr, section_for("wasm32-unknown-unknown")); +} + +namespace +{ +const char* descriptor_section_for(const char* triple) +{ + std::string copy = triple; + return target_descriptor_section(©[0]); +} +} + +TEST(TargetSections, OneDescriptorSectionPerObjectFormat) +{ + EXPECT_STREQ(".data.rel.ro.pony-desc", + descriptor_section_for("x86_64-unknown-linux-gnu")); + EXPECT_STREQ(".data.rel.ro.pony-desc", + descriptor_section_for("aarch64-unknown-freebsd")); + EXPECT_STREQ("__DATA_CONST,__pony_desc", + descriptor_section_for("arm64-apple-macosx")); + EXPECT_STREQ(".ponyc$d", descriptor_section_for("x86_64-pc-windows-msvc")); + EXPECT_EQ(nullptr, descriptor_section_for("wasm32-unknown-unknown")); +} + +class CodegenConstantSectionTest : public PassTest +{}; + +// Descriptors carry the descriptor section, and primitive instances, string +// literals and constant array literals the constant section; the byte arrays +// behind literals and the descriptors' tables carry neither, since the GC never +// visits them as objects. +TEST_F(CodegenConstantSectionTest, ConstantObjectsAreInTheSection) +{ + const char* src = + "primitive P\n" + "actor Main\n" + " let _s: String = \"literal\"\n" + " let _a: Array[U8] val = recover val [as U8: 1; 2; 3] end\n" + " let _p: P = P\n" + " new create(env: Env) => None"; + + TEST_COMPILE(src); + + const char* expected = target_constant_section(compile->opt->triple); + ASSERT_NE(nullptr, expected); + const char* expected_desc = target_descriptor_section(compile->opt->triple); + ASSERT_NE(nullptr, expected_desc); + + auto module = llvm::unwrap(compile->module); + size_t descriptors = 0; + size_t objects = 0; + + for(auto& global : module->globals()) + { + if(global.isDeclaration()) + continue; + + std::string section = global.getSection().str(); + llvm::StringRef name = global.getName(); + + if(name.ends_with("_Desc")) + { + SCOPED_TRACE(name.str()); + EXPECT_EQ(expected_desc, section); + descriptors++; + continue; + } + + // An object starts with a pointer to its descriptor. + auto init = llvm::dyn_cast(global.getInitializer()); + + if((init != nullptr) && (init->getNumOperands() > 0)) + { + auto first = llvm::dyn_cast(init->getOperand(0)); + + if((first != nullptr) && first->getName().ends_with("_Desc")) + { + SCOPED_TRACE(name.str()); + EXPECT_EQ(expected, section); + // ThinLTO won't import a function that refers to a local global with + // a section. + EXPECT_FALSE(global.hasLocalLinkage()); + objects++; + continue; + } + } + + // Anything else, such as a literal's bytes, is outside both sections. + SCOPED_TRACE(name.str()); + EXPECT_NE(expected, section); + EXPECT_NE(expected_desc, section); + } + + EXPECT_GT(descriptors, 0u); + // The string literal, the array literal and P's instance at least. + EXPECT_GE(objects, 3u); +} diff --git a/test/libponyc/noalloc.cc b/test/libponyc/noalloc.cc index 9a17ba42246..fd84c5469f4 100644 --- a/test/libponyc/noalloc.cc +++ b/test/libponyc/noalloc.cc @@ -10,6 +10,8 @@ #include "llvm_config_begin.h" #include +#include +#include #include #include #include @@ -704,3 +706,38 @@ TEST_F(NoAllocLTOTest, NoAllocAssertFailCallPasses) ASSERT_TRUE(runtime_function_is_declaration("ponyint_assert_fail")); ASSERT_FALSE(run_noalloc_check()) << errors_text(); } + +// A call to either allocator for a struct that starts with an embedded field +// is reported as a heap allocation, not as a call into unknown code. +TEST_F(NoAllocLTOTest, SharedStartAllocatorIsAHeapAllocation) +{ + struct allocator_t { const char* name; const char* size_type; }; + + for(const allocator_t& allocator : + {allocator_t{"pony_alloc_small_shared_start", "i32"}, + allocator_t{"pony_alloc_large_shared_start", "i64"}}) + { + SCOPED_TRACE(allocator.name); + std::string name = allocator.name; + std::string size = allocator.size_type; + llvm::LLVMContext ctx; + llvm::SMDiagnostic error; + std::string ir = "declare ptr @" + name + "(ptr, " + size + ")\n" + "define ptr @make(ptr %ctx) #0 {\n" + " %p = call ptr @" + name + "(ptr %ctx, " + size + " 0)\n" + " ret ptr %p\n" + "}\n" + "attributes #0 = { \"pony.noalloc\" }\n"; + auto module = llvm::parseAssemblyString(ir, error, ctx); + ASSERT_NE(nullptr, module) << error.getMessage().str(); + + errors.clear(); + ctx.setDiagnosticHandlerCallBack(noalloc_diag_handler, &errors); + llvm::ModuleAnalysisManager analyses; + pony::NoAllocCheck().run(*module, analyses); + ctx.setDiagnosticHandlerCallBack(nullptr, nullptr); + + EXPECT_EQ(1u, errors.size()); + EXPECT_TRUE(all_errors_report("a heap allocation")) << errors_text(); + } +} diff --git a/test/libponyrt/CMakeLists.txt b/test/libponyrt/CMakeLists.txt index 0735f5aee8c..0abb5facfc4 100644 --- a/test/libponyrt/CMakeLists.txt +++ b/test/libponyrt/CMakeLists.txt @@ -7,6 +7,8 @@ add_executable(libponyrt.tests ds/fun.cc ds/hash.cc ds/list.cc + gc/sections.cc + gc/embed.cc gc/gc.cc gc/marklocal.cc lang/process.cc @@ -31,6 +33,31 @@ target_link_libraries(libponyrt.tests PRIVATE GTest::gtest ) +# On the ELF platforms (all but Windows and macOS), link with the script that +# marks the descriptor and constant sections, as ponyc does when it links a +# program. With a linker that can't use the script, the build links the tests +# without it, and the tests that need the sections skip. +if(NOT MSVC AND NOT APPLE) + include(CheckLinkerFlag) + # Check again on every configure, so a change of linker isn't hidden by a + # cached answer. + unset(PONY_LINKER_TAKES_SECTIONS_SCRIPT CACHE) + check_linker_flag(CXX "LINKER:-T,${PONY_SECTIONS_LINKER_SCRIPT}" + PONY_LINKER_TAKES_SECTIONS_SCRIPT) + if(PONY_LINKER_TAKES_SECTIONS_SCRIPT) + target_link_options(libponyrt.tests + PRIVATE "LINKER:-T,${PONY_SECTIONS_LINKER_SCRIPT}") + set_property(TARGET libponyrt.tests APPEND PROPERTY + LINK_DEPENDS "${PONY_SECTIONS_LINKER_SCRIPT}") + else() + target_compile_definitions(libponyrt.tests + PRIVATE PONY_TESTS_WITHOUT_SECTIONS_SCRIPT) + message(WARNING "The linker can't use ${PONY_SECTIONS_LINKER_SCRIPT}; " + "libponyrt.tests links without it and skips the tests that " + "need it.") + endif() +endif() + if (MSVC) target_link_libraries(libponyrt.tests PRIVATE dbghelp) # The Windows asio backend (sock_notify.c) calls Winsock directly @@ -51,3 +78,21 @@ endif() if (CMAKE_CXX_COMPILER_ID STREQUAL "GNU") target_link_options(libponyrt.tests PRIVATE "-static-libgcc") endif() + +# On the ELF platforms, a program linked with the runtime but without ponyc's +# linker script (PONY_SECTIONS_LINKER_SCRIPT). +if(NOT MSVC AND NOT APPLE) + add_executable(libponyrt.noscript noscript/noscript.c) + target_include_directories(libponyrt.noscript + PRIVATE ../../src/common + PRIVATE ../../src/libponyrt + ) + target_link_libraries(libponyrt.noscript PRIVATE libponyrt) + if(${CMAKE_HOST_SYSTEM_NAME} MATCHES "BSD") + target_link_libraries(libponyrt.noscript PRIVATE execinfo) + elseif(${CMAKE_HOST_SYSTEM_NAME} MATCHES "DragonFly") + target_link_libraries(libponyrt.noscript PRIVATE execinfo atomic) + else() + target_link_libraries(libponyrt.noscript PRIVATE atomic dl) + endif() +endif() diff --git a/test/libponyrt/gc/embed.cc b/test/libponyrt/gc/embed.cc new file mode 100644 index 00000000000..504693fb98c --- /dev/null +++ b/test/libponyrt/gc/embed.cc @@ -0,0 +1,1926 @@ +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include "test_type.h" +#include "test_sections.h" + +// GC visits to objects that share memory with other objects. + +namespace +{ +struct Child +{ + pony_type_t* type; + size_t pad; +}; + +// A class embedded at the start of S. +struct C +{ + pony_type_t* type; + uint64_t x; +}; + +struct S +{ + C c; + Child* d; +}; + +// Allocates as compiled code allocates a struct that starts with an embedded +// field. +void* alloc_shared_start(pony_actor_t* actor, size_t size) +{ + if(size <= HEAP_MAX) + return ponyint_heap_alloc_small_shared_start(actor, &actor->heap, + ponyint_heap_index(size)); + + return ponyint_heap_alloc_large_shared_start(actor, &actor->heap, size); +} + +size_t c_traced; +size_t s_traced; +int field_mutability; + +void trace_c(pony_ctx_t* ctx, void* p) +{ + (void)ctx; + (void)p; + c_traced++; +} + +size_t plain_traces; +size_t routed_traces; + +void count_plain(pony_ctx_t* ctx, void* p, pony_type_t* t, int m) +{ + (void)ctx; + (void)p; + (void)t; + (void)m; + plain_traces++; +} + +void count_routed(pony_ctx_t* ctx, void* p, pony_type_t* t, int m) +{ + (void)ctx; + (void)p; + (void)t; + (void)m; + routed_traces++; +} + +void dispatch_none(pony_ctx_t* ctx, pony_actor_t* actor, pony_msg_t* m) +{ + (void)ctx; + (void)actor; + (void)m; +} + +void trace_s(pony_ctx_t* ctx, void* p) +{ + s_traced++; + S* s = static_cast(p); + // An embedded field is traced in place, as compiled code does. + trace_c(ctx, &s->c); + pony_traceknown(ctx, s->d, s->d->type, field_mutability); +} + +class GcSharedAddress : public testing::Test +{ +protected: + pony_ctx_t* ctx; + pony_actor_t a{}; + pony_actor_t b{}; + _pony_type_t actor_type{}; + _pony_type_t c_type{}; + _pony_type_t s_type{}; + _pony_type_t child_type{}; + _pony_type_t zero_type{}; + + void SetUp() override + { + ponyint_register_thread(); + ctx = pony_ctx(); + ctx->current = &a; + a.type = &actor_type; + b.type = &actor_type; + // An embedded struct with no size, which shares its address with the + // object that holds it. + zero_type.size = 0; + zero_type.might_reference_actor = true; + zero_type.embed_flags = PONY_EMBED_ROUTED; + ponyint_heap_init(&a.heap); + ponyint_heap_init(&b.heap); + ponyint_gc_done(&a.gc); + ponyint_gc_done(&b.gc); + + // Holders trace the fields of these types. + c_type.size = sizeof(C); + c_type.trace = trace_c; + c_type.might_reference_actor = true; + // C is embedded at the start of S. + c_type.embed_flags = PONY_EMBED_ROUTED | PONY_EMBED_AT_START; + s_type.size = sizeof(S); + s_type.trace = trace_s; + s_type.instance = &c_type; + s_type.might_reference_actor = true; + s_type.embed_flags = PONY_EMBED_ROUTED; + child_type.size = sizeof(Child); + child_type.might_reference_actor = true; + + c_traced = 0; + s_traced = 0; + field_mutability = PONY_TRACE_MUTABLE; + } + + void TearDown() override + { + ponyint_gc_free_visits(ctx); + ponyint_actormap_destroy(&ctx->acquire); + ctx->current = NULL; + ctx->msg_target = NULL; + ponyint_gc_destroy(&a.gc); + ponyint_gc_destroy(&b.gc); + ponyint_heap_destroy(&a.heap); + ponyint_heap_destroy(&b.heap); + ponyint_unregister_thread(); + } + + S* alloc_s(pony_actor_t* owner) + { + Child* child = static_cast(ponyint_heap_alloc(owner, &owner->heap, + sizeof(Child), TRACK_NO_FINALISERS)); + child->type = &child_type; + S* s = static_cast(alloc_shared_start(owner, sizeof(S))); + s->c.type = &c_type; + s->c.x = 7; + s->d = child; + return s; + } + + void visit(S* s, bool c_first, int mutability) + { + if(c_first) + { + pony_traceknown_routed(ctx, s, &c_type, mutability); + pony_traceknown_routed(ctx, s, &s_type, mutability); + } else { + pony_traceknown_routed(ctx, s, &s_type, mutability); + pony_traceknown_routed(ctx, s, &c_type, mutability); + } + ponyint_gc_handlestack(ctx); + } + + object_t* local(pony_actor_t* owner, void* p) + { + size_t index = HASHMAP_UNKNOWN; + return ponyint_objectmap_getobject(&owner->gc.local, p, &index); + } + + object_t* foreign(pony_actor_t* holder, pony_actor_t* owner, void* p) + { + size_t index = HASHMAP_UNKNOWN; + actorref_t* aref = ponyint_actormap_getactor(&holder->gc.foreign, owner, + &index); + return (aref == NULL) ? NULL : ponyint_actorref_getobject(aref, p); + } + + // A mark of the owner's own heap starts with every allocation unmarked. + void start_local_mark(pony_actor_t* owner) + { + ponyint_heap_startgc(&owner->heap +#ifdef USE_RUNTIMESTATS + , owner +#endif + ); + ponyint_gc_mark(ctx); + } + + void end_local_mark(pony_actor_t* owner) + { + ponyint_heap_endgc(&owner->heap, 0 +#ifdef USE_RUNTIMESTATS + , owner +#endif + ); + end_epoch(owner); + } + + void end_epoch(pony_actor_t* actor) + { + ponyint_gc_end_visits(ctx); + ponyint_actormap_destroy(&ctx->acquire); + ponyint_gc_done(&actor->gc); + ctx->msg_target = NULL; + } +}; +} + +// Whichever type the mark visits first, the struct's own trace runs once. +TEST_F(GcSharedAddress, MarkTracesStructAfterItsFirstField) +{ + for(bool c_first : {true, false}) + { + SCOPED_TRACE(c_first ? "C first" : "S first"); + S* s = alloc_s(&a); + s_traced = 0; + field_mutability = PONY_TRACE_MUTABLE; + start_local_mark(&a); + visit(s, c_first, PONY_TRACE_MUTABLE); + EXPECT_EQ(1u, s_traced); + // The struct's trace marked d. + EXPECT_EQ(HEAP_MARK_MARKED, + ponyint_heap_mark_plain(ponyint_pagemap_get_chunk(s->d), s->d)); + // The visit as the struct's own type marked its allocation, so neither + // visit was recorded in the visit set. + EXPECT_EQ(HEAP_MARK_MARKED, + ponyint_heap_mark_plain(ponyint_pagemap_get_chunk(s), s)); + EXPECT_EQ(0u, ctx->visits.count); + end_local_mark(&a); + } +} + +// A mark that records many visits grows the set that holds them and still +// finds every one; a later mark that records few gives the storage back. +TEST_F(GcSharedAddress, VisitSetGrowsAndShrinks) +{ + const size_t count = 100; + S* objects[count]; + for(size_t i = 0; i < count; i++) + objects[i] = alloc_s(&a); + + start_local_mark(&a); + + // Each struct's first field is visited twice before the struct. Both visits + // trace it; the second is recorded in the set, which grows. + for(size_t i = 0; i < count; i++) + { + pony_traceknown_routed(ctx, objects[i], &c_type, PONY_TRACE_MUTABLE); + pony_traceknown_routed(ctx, objects[i], &c_type, PONY_TRACE_MUTABLE); + } + + ponyint_gc_handlestack(ctx); + EXPECT_EQ(count * 2, c_traced); + EXPECT_EQ(count, ctx->visits.count); + EXPECT_GE(ctx->visits.capacity, count * 2); + + // A third visit to each finds its record and doesn't trace again. + for(size_t i = 0; i < count; i++) + pony_traceknown_routed(ctx, objects[i], &c_type, PONY_TRACE_MUTABLE); + + ponyint_gc_handlestack(ctx); + EXPECT_EQ(count * 2, c_traced); + + for(size_t i = 0; i < count; i++) + pony_traceknown_routed(ctx, objects[i], &s_type, PONY_TRACE_MUTABLE); + + ponyint_gc_handlestack(ctx); + EXPECT_EQ(count, s_traced); + end_local_mark(&a); + EXPECT_GE(ctx->visits.capacity, count * 2); + + // The next mark traces the struct again. + s_traced = 0; + start_local_mark(&a); + pony_traceknown_routed(ctx, objects[0], &c_type, PONY_TRACE_MUTABLE); + pony_traceknown_routed(ctx, objects[0], &s_type, PONY_TRACE_MUTABLE); + ponyint_gc_handlestack(ctx); + EXPECT_EQ(1u, s_traced); + end_local_mark(&a); + EXPECT_EQ(0u, ctx->visits.capacity); +} + +// A record from one mark doesn't survive into the next: a repeat visit there +// is traced again. +TEST_F(GcSharedAddress, VisitSetKeepsNoRecordAcrossMarks) +{ + const size_t count = 100; + S* objects[count]; + for(size_t i = 0; i < count; i++) + objects[i] = alloc_s(&a); + + // Enough records that the set keeps its storage after this mark. + start_local_mark(&a); + for(size_t i = 0; i < count; i++) + { + pony_traceknown_routed(ctx, objects[i], &c_type, PONY_TRACE_MUTABLE); + pony_traceknown_routed(ctx, objects[i], &c_type, PONY_TRACE_MUTABLE); + } + ponyint_gc_handlestack(ctx); + end_local_mark(&a); + ASSERT_GE(ctx->visits.capacity, count * 2); + + c_traced = 0; + start_local_mark(&a); + pony_traceknown_routed(ctx, objects[0], &c_type, PONY_TRACE_MUTABLE); + pony_traceknown_routed(ctx, objects[0], &c_type, PONY_TRACE_MUTABLE); + ponyint_gc_handlestack(ctx); + EXPECT_EQ(2u, c_traced); + end_local_mark(&a); +} + +// The end of an actor's mark empties the visit set. +TEST_F(GcSharedAddress, MarkDoneEmptiesTheVisitSet) +{ + S* s = alloc_s(&a); + + start_local_mark(&a); + pony_traceknown_routed(ctx, s, &c_type, PONY_TRACE_MUTABLE); + pony_traceknown_routed(ctx, s, &c_type, PONY_TRACE_MUTABLE); + ASSERT_NE(0u, ctx->visits.count); + ponyint_mark_done(ctx); + EXPECT_EQ(0u, ctx->visits.count); + + ponyint_heap_endgc(&a.heap, 0 +#ifdef USE_RUNTIMESTATS + , &a +#endif + ); +} + +namespace +{ +// A struct that starts with a struct that starts with C: three types share +// one address. +struct T +{ + S s; + Child* e; +}; + +size_t t_traced; + +void trace_t(pony_ctx_t* ctx, void* p) +{ + t_traced++; + T* t = static_cast(p); + trace_s(ctx, &t->s); + pony_traceknown(ctx, t->e, t->e->type, field_mutability); +} +} + +class GcNestedSharedAddress : public GcSharedAddress +{ +protected: + _pony_type_t inner_s_type{}; + _pony_type_t t_type{}; + + void SetUp() override + { + GcSharedAddress::SetUp(); + // S embedded at T's start. + inner_s_type = s_type; + inner_s_type.embed_flags = PONY_EMBED_ROUTED | PONY_EMBED_AT_START; + t_type.size = sizeof(T); + t_type.trace = trace_t; + t_type.instance = &inner_s_type; + t_type.might_reference_actor = true; + t_type.embed_flags = PONY_EMBED_ROUTED; + t_traced = 0; + } + + T* alloc_t(pony_actor_t* owner) + { + Child* d = static_cast(ponyint_heap_alloc(owner, &owner->heap, + sizeof(Child), TRACK_NO_FINALISERS)); + d->type = &child_type; + Child* e = static_cast(ponyint_heap_alloc(owner, &owner->heap, + sizeof(Child), TRACK_NO_FINALISERS)); + e->type = &child_type; + T* t = static_cast(alloc_shared_start(owner, sizeof(T))); + t->s.c.type = &c_type; + t->s.c.x = 7; + t->s.d = d; + t->e = e; + return t; + } +}; + +// The visit set keys a visit by address and type: repeat visits as C don't +// hide a visit as S at the same address. +TEST_F(GcNestedSharedAddress, VisitSetKeysByType) +{ + T* t = alloc_t(&a); + start_local_mark(&a); + pony_traceknown_routed(ctx, t, &c_type, PONY_TRACE_MUTABLE); + pony_traceknown_routed(ctx, t, &c_type, PONY_TRACE_MUTABLE); + pony_traceknown_routed(ctx, t, &inner_s_type, PONY_TRACE_MUTABLE); + ponyint_gc_handlestack(ctx); + EXPECT_EQ(1u, s_traced); + EXPECT_EQ(HEAP_MARK_MARKED, + ponyint_heap_mark_plain(ponyint_pagemap_get_chunk(t->s.d), t->s.d)); + end_local_mark(&a); +} + +// A send that visits the innermost field first and then the outermost struct +// traces the outer struct: it encloses the field through two levels. +TEST_F(GcNestedSharedAddress, SendRetracesThroughTwoLevels) +{ + field_mutability = PONY_TRACE_IMMUTABLE; + T* t = alloc_t(&a); + ctx->current = &a; + pony_gc_send(ctx, &b); + pony_traceknown_routed(ctx, t, &c_type, PONY_TRACE_IMMUTABLE); + pony_traceknown_routed(ctx, t, &t_type, PONY_TRACE_IMMUTABLE); + ponyint_gc_handlestack(ctx); + EXPECT_EQ(1u, t_traced); + object_t* e = local(&a, t->e); + ASSERT_NE(nullptr, e); + EXPECT_EQ(1u, e->rc); + end_epoch(&a); +} + +// An immutable root embedded in the actor that owns it has no heap chunk. The +// owner's mark leaves it to the actor's own trace. +TEST_F(GcSharedAddress, ImmutableRootWithoutAChunk) +{ + _pony_type_t root_type = c_type; + root_type.might_reference_actor = false; + root_type.embed_flags = PONY_EMBED_IN_ACTOR; + C inside{}; + inside.type = &root_type; + object_t* obj = ponyint_objectmap_getorput(&a.gc.local, &inside, &root_type); + obj->immutable = true; + obj->rc = 1; + + start_local_mark(&a); + ponyint_gc_markimmutable(ctx, &a.gc); + ponyint_gc_handlestack(ctx); + EXPECT_EQ(0u, c_traced); + end_local_mark(&a); +} + +// A routed type is never an immutable root, even without +// might_reference_actor: the type the object map records for its address can +// be the field at a struct's start rather than the struct. +TEST_F(GcSharedAddress, RoutedTypeIsNeverAnImmutableRoot) +{ + _pony_type_t routed_type = c_type; + routed_type.might_reference_actor = false; + _pony_type_t plain_type = c_type; + plain_type.might_reference_actor = false; + plain_type.embed_flags = 0; + + S* s = alloc_s(&a); + S* t = alloc_s(&a); + object_t* routed = ponyint_objectmap_getorput(&a.gc.local, s, &routed_type); + routed->immutable = true; + routed->rc = 1; + object_t* plain = ponyint_objectmap_getorput(&a.gc.local, t, &plain_type); + plain->immutable = true; + plain->rc = 1; + + size_t i = HASHMAP_BEGIN; + EXPECT_EQ(plain, ponyint_gc_next_immutable_root(&a.gc, &i)); + EXPECT_EQ(nullptr, ponyint_gc_next_immutable_root(&a.gc, &i)); + end_epoch(&a); +} + +// Sending and receiving visits as both types count the struct's field once on +// each side, so the counts match. +TEST_F(GcSharedAddress, SendAndReceiveCountStructFieldOnce) +{ + // A failed ASSERT returns from run, so the other order is still checked. + auto run = [&](bool c_first) + { + field_mutability = PONY_TRACE_IMMUTABLE; + S* s = alloc_s(&a); + + ctx->current = &a; + pony_gc_send(ctx, &b); + visit(s, c_first, PONY_TRACE_IMMUTABLE); + object_t* sent = local(&a, s->d); + ASSERT_NE(nullptr, sent); + EXPECT_EQ(1u, sent->rc); + ASSERT_NE(nullptr, local(&a, s)); + EXPECT_EQ(1u, local(&a, s)->rc); + end_epoch(&a); + + ctx->current = &b; + pony_gc_recv(ctx); + visit(s, c_first, PONY_TRACE_IMMUTABLE); + object_t* received = foreign(&b, &a, s->d); + ASSERT_NE(nullptr, received); + EXPECT_EQ(1u, received->rc); + ASSERT_NE(nullptr, foreign(&b, &a, s)); + EXPECT_EQ(1u, foreign(&b, &a, s)->rc); + end_epoch(&b); + ctx->current = &a; + }; + + for(bool c_first : {true, false}) + { + SCOPED_TRACE(c_first ? "C first" : "S first"); + run(c_first); + } +} + +// An actor that gets its own object back in a message counts the struct's +// field once, whichever type is visited first, so the counts return to zero. +TEST_F(GcSharedAddress, ReceivingOwnObjectCountsStructFieldOnce) +{ + // A failed ASSERT returns from run, so the other order is still checked. + auto run = [&](bool c_first) + { + field_mutability = PONY_TRACE_IMMUTABLE; + S* s = alloc_s(&a); + + ctx->current = &a; + pony_gc_send(ctx, &b); + visit(s, c_first, PONY_TRACE_IMMUTABLE); + end_epoch(&a); + ASSERT_NE(nullptr, local(&a, s->d)); + ASSERT_EQ(1u, local(&a, s->d)->rc); + + pony_gc_recv(ctx); + visit(s, c_first, PONY_TRACE_IMMUTABLE); + EXPECT_EQ(0u, local(&a, s->d)->rc); + EXPECT_EQ(0u, local(&a, s)->rc); + end_epoch(&a); + }; + + for(bool c_first : {true, false}) + { + SCOPED_TRACE(c_first ? "C first" : "S first"); + run(c_first); + } +} + +// A type recorded for the address in an earlier epoch doesn't stop a later +// epoch from tracing the struct when its first field is visited first. +TEST_F(GcSharedAddress, EarlierEpochTypeDoesNotBlockTheStructTrace) +{ + field_mutability = PONY_TRACE_IMMUTABLE; + S* s = alloc_s(&a); + + ctx->current = &a; + pony_gc_send(ctx, &b); + pony_traceknown_routed(ctx, s, &s_type, PONY_TRACE_IMMUTABLE); + ponyint_gc_handlestack(ctx); + end_epoch(&a); + ASSERT_NE(nullptr, local(&a, s->d)); + ASSERT_EQ(1u, local(&a, s->d)->rc); + + pony_gc_send(ctx, &b); + visit(s, true, PONY_TRACE_IMMUTABLE); + EXPECT_EQ(2u, local(&a, s->d)->rc); + end_epoch(&a); +} + +// An actor holding another actor's struct and that struct's first field marks +// the struct's other field in every collection, including after an earlier +// collection recorded the struct's type for the address. +TEST_F(GcSharedAddress, RemoteMarkTracesStructAfterItsFirstField) +{ + field_mutability = PONY_TRACE_MUTABLE; + S* s = alloc_s(&b); + actorref_t* aref = ponyint_actormap_getorput(&a.gc.foreign, &b); + aref->rc = GC_INC_MORE; + object_t* obj = ponyint_actorref_getorput(aref, s, &s_type); + obj->rc = GC_INC_MORE; + object_t* d = ponyint_actorref_getorput(aref, s->d, &child_type); + d->rc = GC_INC_MORE; + + for(bool c_first : {true, false, true}) + { + SCOPED_TRACE(c_first ? "C first" : "S first"); + ctx->current = &a; + ponyint_gc_mark(ctx); + visit(s, c_first, PONY_TRACE_MUTABLE); + EXPECT_TRUE(ponyint_object_marked(d, a.gc.mark)); + end_epoch(&a); + } +} + +// pony_traceknown_routed traces an object with no size as opaque whatever +// mode it is given, so the struct's field is still counted when it is sent. +TEST_F(GcSharedAddress, ZeroSizeVisitIsOpaqueWhateverTheMode) +{ + field_mutability = PONY_TRACE_IMMUTABLE; + S* s = alloc_s(&a); + pony_gc_send(ctx, &b); + pony_traceknown_routed(ctx, s, &zero_type, PONY_TRACE_MUTABLE); + pony_traceknown_routed(ctx, s, &s_type, PONY_TRACE_IMMUTABLE); + ponyint_gc_handlestack(ctx); + ASSERT_NE(nullptr, local(&a, s->d)); + EXPECT_EQ(1u, local(&a, s->d)->rc); + ASSERT_NE(nullptr, local(&a, s)); + EXPECT_EQ(&s_type, local(&a, s)->type); + end_epoch(&a); +} + +// pony_traceknown_routed takes an actor's type, as C code calls it for any +// type: the actor is counted as a reference to another actor. +TEST_F(GcSharedAddress, RoutedEntryPointTakesAnActor) +{ + actor_type.dispatch = dispatch_none; + pony_gc_recv(ctx); + pony_traceknown_routed(ctx, &b, &actor_type, PONY_TRACE_OPAQUE); + ponyint_gc_handlestack(ctx); + size_t index = HASHMAP_UNKNOWN; + actorref_t* aref = ponyint_actormap_getactor(&a.gc.foreign, &b, &index); + ASSERT_NE(nullptr, aref); + EXPECT_GT(aref->rc, 0u); + EXPECT_EQ(nullptr, local(&a, &b)); + end_epoch(&a); +} + +// The routed entry points take a type that isn't routed, as C code calls them +// without knowing which types are, and send it to the plain trace. +TEST_F(GcSharedAddress, RoutedEntryPointTakesAPlainType) +{ + Child* child = static_cast(ponyint_heap_alloc(&a, &a.heap, + sizeof(Child), TRACK_NO_FINALISERS)); + child->type = &child_type; + pony_gc_send(ctx, &b); + + trace_object_fn plain = ctx->trace_object; + trace_object_fn routed = ctx->trace_routed; + ctx->trace_object = count_plain; + ctx->trace_routed = count_routed; + plain_traces = 0; + routed_traces = 0; + pony_traceknown_routed(ctx, child, &child_type, PONY_TRACE_MUTABLE); + pony_traceunknown_routed(ctx, child, PONY_TRACE_MUTABLE); + ctx->trace_object = plain; + ctx->trace_routed = routed; + EXPECT_EQ(2u, plain_traces); + EXPECT_EQ(0u, routed_traces); + + pony_traceunknown_routed(ctx, child, PONY_TRACE_MUTABLE); + ponyint_gc_handlestack(ctx); + ASSERT_NE(nullptr, local(&a, child)); + EXPECT_EQ(1u, local(&a, child)->rc); + end_epoch(&a); +} + +// pony_traceunknown_routed takes an actor, found by its descriptor: the actor +// is counted as a reference to another actor. +TEST_F(GcSharedAddress, UnknownRoutedEntryPointTakesAnActor) +{ + actor_type.dispatch = dispatch_none; + pony_gc_recv(ctx); + pony_traceunknown_routed(ctx, &b, PONY_TRACE_OPAQUE); + ponyint_gc_handlestack(ctx); + size_t index = HASHMAP_UNKNOWN; + actorref_t* aref = ponyint_actormap_getactor(&a.gc.foreign, &b, &index); + ASSERT_NE(nullptr, aref); + EXPECT_GT(aref->rc, 0u); + EXPECT_EQ(nullptr, local(&a, &b)); + end_epoch(&a); +} + +// An opaque visit to an object with no size at the struct's address doesn't +// mark the address as traced: the struct's field is still counted when it is +// sent. +TEST_F(GcSharedAddress, ZeroSizeVisitDoesNotHideTheStruct) +{ + field_mutability = PONY_TRACE_IMMUTABLE; + S* s = alloc_s(&a); + pony_gc_send(ctx, &b); + pony_traceknown_routed(ctx, s, &zero_type, PONY_TRACE_OPAQUE); + pony_traceknown_routed(ctx, s, &s_type, PONY_TRACE_IMMUTABLE); + ponyint_gc_handlestack(ctx); + ASSERT_NE(nullptr, local(&a, s->d)); + EXPECT_EQ(1u, local(&a, s->d)->rc); + // The object map records the struct's type for the shared address, not the + // empty one visited first. + ASSERT_NE(nullptr, local(&a, s)); + EXPECT_EQ(&s_type, local(&a, s)->type); + end_epoch(&a); + + // The same holds for the actor that receives them. + ctx->current = &b; + pony_gc_recv(ctx); + pony_traceknown_routed(ctx, s, &zero_type, PONY_TRACE_OPAQUE); + pony_traceknown_routed(ctx, s, &s_type, PONY_TRACE_IMMUTABLE); + ponyint_gc_handlestack(ctx); + ASSERT_NE(nullptr, foreign(&b, &a, s)); + EXPECT_EQ(&s_type, foreign(&b, &a, s)->type); + end_epoch(&b); + ctx->current = &a; +} + +// Start and end a collection of one actor's heap. +namespace +{ +void start_gc(pony_actor_t* actor) +{ + ponyint_heap_startgc(&actor->heap +#ifdef USE_RUNTIMESTATS + , actor +#endif + ); +} + +void end_gc(pony_actor_t* actor) +{ + ponyint_heap_endgc(&actor->heap, 0 +#ifdef USE_RUNTIMESTATS + , actor +#endif + ); +} +} + +// An allocation whose start is shared is marked only by a visit of its own +// type, is kept while its start is visited, and loses the record when it is +// freed, so a later allocation in the same slot is marked as usual. +TEST(HeapMarkVisit, SharedStartLastsAsLongAsTheAllocation) +{ + // 16 KiB is a large allocation, whose freed chunk the heap reuses for the + // next allocation of that size. + static_assert(16384 > HEAP_MAX, "16 KiB must be a large allocation"); + for(size_t size : {(size_t)64, (size_t)16384}) + { + SCOPED_TRACE(size); + ponyint_register_thread(); + pony_actor_t actor{}; + _pony_type_t type{}; + actor.type = &type; + ponyint_heap_init(&actor.heap); + + // Another allocation, kept throughout, so a small chunk stays in use and + // the freed slot is reused inside it. + char* keeper = static_cast(ponyint_heap_alloc(&actor, &actor.heap, + size, TRACK_NO_FINALISERS)); + char* p = static_cast(alloc_shared_start(&actor, size)); + chunk_t* chunk = ponyint_pagemap_get_chunk(p); + chunk_t* keeper_chunk = ponyint_pagemap_get_chunk(keeper); + + // Each collection that visits its start keeps it, and it stays recorded. + // A visit of the allocation's own type marks it, and every later visit + // finds it marked. + for(int i = 0; i < 2; i++) + { + start_gc(&actor); + ponyint_heap_mark_routed(keeper_chunk, keeper, true); + EXPECT_EQ(HEAP_MARK_SHARED_START_FIRST, + ponyint_heap_mark_routed(chunk, p, true)); + EXPECT_EQ(HEAP_MARK_SHARED_START, + ponyint_heap_mark_routed(chunk, p, true)); + EXPECT_EQ(HEAP_MARK_NEW, ponyint_heap_mark_routed(chunk, p, false)); + EXPECT_EQ(HEAP_MARK_MARKED, ponyint_heap_mark_routed(chunk, p, true)); + EXPECT_EQ(HEAP_MARK_MARKED, ponyint_heap_mark_routed(chunk, p, false)); + end_gc(&actor); + } + + // A collection that doesn't visit it frees it. An allocation that reuses + // the memory is marked as usual. + start_gc(&actor); + ponyint_heap_mark_routed(keeper_chunk, keeper, true); + end_gc(&actor); + + char* q = static_cast(ponyint_heap_alloc(&actor, &actor.heap, + size, TRACK_NO_FINALISERS)); + ASSERT_EQ(p, q); + chunk = ponyint_pagemap_get_chunk(q); + start_gc(&actor); + EXPECT_EQ(HEAP_MARK_NEW, ponyint_heap_mark_routed(chunk, q, true)); + end_gc(&actor); + + ponyint_heap_destroy(&actor.heap); + ponyint_unregister_thread(); + } +} + +// The allocators compiled code calls for a struct that starts with an +// embedded field record its shared start. +TEST(HeapMarkVisit, SharedStartAllocatorsRecordTheSharedStart) +{ + ponyint_register_thread(); + pony_ctx_t* ctx = pony_ctx(); + pony_actor_t actor{}; + _pony_type_t type{}; + actor.type = &type; + ponyint_heap_init(&actor.heap); + ctx->current = &actor; + + char* small = static_cast(pony_alloc_small_shared_start(ctx, + ponyint_heap_index(64))); + char* large = static_cast(pony_alloc_large_shared_start(ctx, + HEAP_MAX * 2)); + + start_gc(&actor); + EXPECT_EQ(HEAP_MARK_SHARED_START_FIRST, + ponyint_heap_mark_routed(ponyint_pagemap_get_chunk(small), small, true)); + EXPECT_EQ(HEAP_MARK_SHARED_START_FIRST, + ponyint_heap_mark_routed(ponyint_pagemap_get_chunk(large), large, true)); + end_gc(&actor); + + ctx->current = NULL; + ponyint_heap_destroy(&actor.heap); + ponyint_unregister_thread(); +} + +// An interior visit keeps its allocation through the sweep. +TEST(HeapMarkVisit, InteriorVisitKeepsAllocation) +{ + ponyint_register_thread(); + pony_actor_t actor{}; + _pony_type_t type{}; + actor.type = &type; + ponyint_heap_init(&actor.heap); + + for(size_t size : {(size_t)64, (size_t)HEAP_MAX * 2}) + { + SCOPED_TRACE(size); + char* p = static_cast(ponyint_heap_alloc(&actor, &actor.heap, size, + TRACK_NO_FINALISERS)); + chunk_t* chunk = ponyint_pagemap_get_chunk(p); + start_gc(&actor); + EXPECT_EQ(HEAP_MARK_INTERIOR_FIRST, + ponyint_heap_mark_routed(chunk, p + 16, true)); + end_gc(&actor); + void* next = ponyint_heap_alloc(&actor, &actor.heap, size, + TRACK_NO_FINALISERS); + EXPECT_NE(static_cast(p), next); + } + + ponyint_heap_destroy(&actor.heap); + ponyint_unregister_thread(); +} + +TEST(HeapMarkVisit, ReportsInteriorPointers) +{ + ponyint_register_thread(); + pony_actor_t actor{}; + _pony_type_t type{}; + actor.type = &type; + ponyint_heap_init(&actor.heap); + + // The plain mark reports interior pointers the same way. + for(bool plain : {false, true}) + { + for(size_t size : {(size_t)64, (size_t)HEAP_MAX * 2}) + { + SCOPED_TRACE(plain ? "plain" : "routed"); + SCOPED_TRACE(size); + char* p = static_cast(ponyint_heap_alloc(&actor, &actor.heap, + size, TRACK_NO_FINALISERS)); + chunk_t* chunk = ponyint_pagemap_get_chunk(p); + auto mark = [&](char* q) + { + return plain ? ponyint_heap_mark_plain(chunk, q) : + ponyint_heap_mark_routed(chunk, q, true); + }; + start_gc(&actor); + EXPECT_EQ(HEAP_MARK_INTERIOR_FIRST, mark(p + 16)); + EXPECT_EQ(HEAP_MARK_INTERIOR, mark(p + 16)); + EXPECT_EQ(HEAP_MARK_NEW, mark(p)); + EXPECT_EQ(HEAP_MARK_MARKED, mark(p)); + EXPECT_EQ(HEAP_MARK_COVERED, mark(p + 16)); + end_gc(&actor); + } + } + + ponyint_heap_destroy(&actor.heap); + ponyint_unregister_thread(); +} + +// The plain mark is for types that can't be at a shared start, so it marks +// such an allocation on the first visit to its start. +TEST(HeapMarkVisit, PlainMarkMarksASharedStart) +{ + ponyint_register_thread(); + pony_actor_t actor{}; + _pony_type_t type{}; + actor.type = &type; + ponyint_heap_init(&actor.heap); + + for(size_t size : {(size_t)64, (size_t)HEAP_MAX * 2}) + { + SCOPED_TRACE(size); + char* p = static_cast(alloc_shared_start(&actor, size)); + chunk_t* chunk = ponyint_pagemap_get_chunk(p); + start_gc(&actor); + EXPECT_EQ(HEAP_MARK_NEW, ponyint_heap_mark_plain(chunk, p)); + EXPECT_EQ(HEAP_MARK_MARKED, ponyint_heap_mark_plain(chunk, p)); + end_gc(&actor); + } + + ponyint_heap_destroy(&actor.heap); + ponyint_unregister_thread(); +} + +// A small slot with a finaliser uses the same bit for "fully constructed" that +// a slot without one uses for a shared start. A routed visit to the start of +// such a slot still marks it: the bit isn't read as a shared start. +TEST(HeapMarkVisit, FinaliserSlotIsNotASharedStart) +{ + ponyint_register_thread(); + pony_ctx_t* ctx = pony_ctx(); + pony_actor_t actor{}; + _pony_type_t actor_type{}; + actor.type = &actor_type; + ponyint_heap_init(&actor.heap); + ctx->current = &actor; + + _pony_type_t type{}; + type.final = [](void*) {}; + void** p = static_cast(ponyint_heap_alloc(&actor, &actor.heap, 64, + TRACK_ALL_FINALISERS)); + *p = &type; + ponyint_gc_final_ready(ctx, p); + chunk_t* chunk = ponyint_pagemap_get_chunk(p); + + // The slot's traceable bit is set, the bit a shared-start read could misread. + bool traceable = false; + ponyint_heap_visit_finalisers(&actor.heap, + [](void* arg, void*, bool t) { *static_cast(arg) = t; return true; }, + &traceable, nullptr); + ASSERT_TRUE(traceable); + + start_gc(&actor); + EXPECT_EQ(HEAP_MARK_NEW, ponyint_heap_mark_routed(chunk, p, true)); + end_gc(&actor); + + ctx->current = NULL; + ponyint_heap_destroy(&actor.heap); + ponyint_unregister_thread(); +} + +// A shallow mark doesn't mark the allocation: a later visit to its start marks +// it, except a routed visit that may be the start field at a shared start, and +// no later visit is reported as the first. +TEST(HeapMarkVisit, ShallowMarkLeavesTheAllocationToMark) +{ + ponyint_register_thread(); + pony_actor_t actor{}; + _pony_type_t type{}; + actor.type = &type; + ponyint_heap_init(&actor.heap); + + for(size_t size : {(size_t)64, (size_t)HEAP_MAX * 2}) + { + SCOPED_TRACE(size); + char* p = static_cast(ponyint_heap_alloc(&actor, &actor.heap, + size, TRACK_NO_FINALISERS)); + chunk_t* chunk = ponyint_pagemap_get_chunk(p); + + start_gc(&actor); + ponyint_heap_mark_shallow(chunk, p); + EXPECT_EQ(HEAP_MARK_INTERIOR, + ponyint_heap_mark_routed(chunk, p + 16, true)); + EXPECT_EQ(HEAP_MARK_NEW, ponyint_heap_mark_plain(chunk, p)); + EXPECT_EQ(HEAP_MARK_COVERED, ponyint_heap_mark_plain(chunk, p + 16)); + end_gc(&actor); + + // The start isn't shared, so a routed visit that may be the start field + // marks it too. + start_gc(&actor); + ponyint_heap_mark_shallow(chunk, p); + EXPECT_EQ(HEAP_MARK_NEW, ponyint_heap_mark_routed(chunk, p, true)); + end_gc(&actor); + + char* q = static_cast(alloc_shared_start(&actor, size)); + chunk_t* q_chunk = ponyint_pagemap_get_chunk(q); + + start_gc(&actor); + ponyint_heap_mark_shallow(q_chunk, q); + EXPECT_EQ(HEAP_MARK_SHARED_START, + ponyint_heap_mark_routed(q_chunk, q, true)); + EXPECT_EQ(HEAP_MARK_NEW, ponyint_heap_mark_routed(q_chunk, q, false)); + end_gc(&actor); + + start_gc(&actor); + ponyint_heap_mark_shallow(q_chunk, q); + EXPECT_EQ(HEAP_MARK_NEW, ponyint_heap_mark_plain(q_chunk, q)); + end_gc(&actor); + } + + ponyint_heap_destroy(&actor.heap); + ponyint_unregister_thread(); +} + +// A trace of an interface-typed reference reads the descriptor at run time. +// C's descriptor has PONY_EMBED_ROUTED and PONY_EMBED_AT_START, so the trace +// doesn't mark S's allocation when it reaches C at S's address, and a visit as +// S still traces S's other field. +TEST_F(GcSharedAddress, UnknownTraceOfTheFirstFieldLeavesTheStructToTrace) +{ + S* s = alloc_s(&a); + start_local_mark(&a); + pony_traceunknown_routed(ctx, s, PONY_TRACE_MUTABLE); + pony_traceknown_routed(ctx, s, &s_type, PONY_TRACE_MUTABLE); + ponyint_gc_handlestack(ctx); + EXPECT_EQ(1u, s_traced); + EXPECT_EQ(HEAP_MARK_MARKED, + ponyint_heap_mark_plain(ponyint_pagemap_get_chunk(s->d), s->d)); + end_local_mark(&a); +} + +// The object map can record a struct's address as the type of its first field. +// If the owner marked that entry as an immutable root, it would trace only the +// field and mark the struct's allocation, and the struct's other field would +// be freed. +TEST_F(GcSharedAddress, ImmutableEntryAsTheFirstFieldLeavesTheStructToTrace) +{ + _pony_type_t routed_c = c_type; + routed_c.might_reference_actor = false; + S* s = alloc_s(&a); + object_t* obj = ponyint_objectmap_getorput(&a.gc.local, s, &routed_c); + obj->immutable = true; + obj->rc = 1; + + start_local_mark(&a); + ponyint_gc_markimmutable(ctx, &a.gc); + pony_traceknown_routed(ctx, s, &s_type, PONY_TRACE_MUTABLE); + ponyint_gc_handlestack(ctx); + EXPECT_EQ(1u, s_traced); + EXPECT_EQ(HEAP_MARK_MARKED, + ponyint_heap_mark_plain(ponyint_pagemap_get_chunk(s->d), s->d)); + end_local_mark(&a); +} + +// Another actor's struct sent as its first field, mutable, and then as the +// struct, immutable: the second visit traces the struct but borrows nothing +// more and doesn't make the object immutable. +TEST_F(GcSharedAddress, SendRepeatAsTheStructBorrowsNothingMore) +{ + S* s = alloc_s(&b); + actorref_t* aref = ponyint_actormap_getorput(&a.gc.foreign, &b); + aref->rc = GC_INC_MORE; + object_t* obj = ponyint_actorref_getorput(aref, s, &c_type); + obj->rc = GC_INC_MORE; + object_t* d = ponyint_actorref_getorput(aref, s->d, &child_type); + d->rc = GC_INC_MORE; + + ctx->current = &a; + pony_gc_send(ctx, &b); + pony_traceknown_routed(ctx, s, &c_type, PONY_TRACE_MUTABLE); + pony_traceknown_routed(ctx, s, &s_type, PONY_TRACE_IMMUTABLE); + ponyint_gc_handlestack(ctx); + EXPECT_EQ(1u, s_traced); + EXPECT_EQ(GC_INC_MORE - 1, obj->rc); + EXPECT_FALSE(obj->immutable); + end_epoch(&a); +} + +// The same visits in a mark of another actor's struct acquire nothing more. +TEST_F(GcSharedAddress, RemoteMarkRepeatAsTheStructAcquiresNothingMore) +{ + S* s = alloc_s(&b); + actorref_t* aref = ponyint_actormap_getorput(&a.gc.foreign, &b); + aref->rc = GC_INC_MORE; + object_t* obj = ponyint_actorref_getorput(aref, s, &c_type); + obj->rc = GC_INC_MORE; + object_t* d = ponyint_actorref_getorput(aref, s->d, &child_type); + d->rc = GC_INC_MORE; + + ctx->current = &a; + ponyint_gc_mark(ctx); + pony_traceknown_routed(ctx, s, &c_type, PONY_TRACE_MUTABLE); + pony_traceknown_routed(ctx, s, &s_type, PONY_TRACE_IMMUTABLE); + ponyint_gc_handlestack(ctx); + EXPECT_EQ(1u, s_traced); + EXPECT_EQ(GC_INC_MORE, obj->rc); + EXPECT_FALSE(obj->immutable); + end_epoch(&a); +} + +namespace +{ +// A class embedded in a class. b_type is routed, as it is when B is also +// embedded at the start of a struct elsewhere in the program. +struct B +{ + pony_type_t* type; + uint64_t x; +}; + +struct A +{ + pony_type_t* type; + B b; + Child* d; +}; + +size_t a_traced; +size_t b_traced; + +void trace_b(pony_ctx_t* ctx, void* p) +{ + (void)ctx; + (void)p; + b_traced++; +} + +void trace_a(pony_ctx_t* ctx, void* p) +{ + a_traced++; + A* a = static_cast(p); + trace_b(ctx, &a->b); + pony_traceknown(ctx, a->d, a->d->type, PONY_TRACE_MUTABLE); +} + +class GcEmbeddedInClass : public testing::Test +{ +protected: + pony_ctx_t* ctx; + pony_actor_t a{}; + _pony_type_t actor_type{}; + _pony_type_t a_type{}; + _pony_type_t b_type{}; + _pony_type_t child_type{}; + + void SetUp() override + { + ponyint_register_thread(); + ctx = pony_ctx(); + ctx->current = &a; + a.type = &actor_type; + ponyint_heap_init(&a.heap); + ponyint_gc_done(&a.gc); + + a_type.size = sizeof(A); + a_type.trace = trace_a; + a_type.might_reference_actor = true; + b_type.size = sizeof(B); + b_type.trace = trace_b; + b_type.might_reference_actor = true; + b_type.embed_flags = PONY_EMBED_ROUTED; + child_type.size = sizeof(Child); + child_type.might_reference_actor = true; + a_traced = 0; + b_traced = 0; + } + + void TearDown() override + { + ponyint_gc_free_visits(ctx); + ponyint_actormap_destroy(&ctx->acquire); + ctx->current = NULL; + ponyint_gc_destroy(&a.gc); + ponyint_heap_destroy(&a.heap); + ponyint_unregister_thread(); + } + + A* alloc_a() + { + Child* child = static_cast(ponyint_heap_alloc(&a, &a.heap, + sizeof(Child), TRACK_NO_FINALISERS)); + child->type = &child_type; + A* obj = static_cast(ponyint_heap_alloc(&a, &a.heap, sizeof(A), + TRACK_NO_FINALISERS)); + obj->type = &a_type; + obj->b.type = &b_type; + obj->d = child; + return obj; + } + + void start_mark() + { + ponyint_heap_startgc(&a.heap +#ifdef USE_RUNTIMESTATS + , &a +#endif + ); + ponyint_gc_mark(ctx); + } + + void end_mark() + { + ponyint_heap_endgc(&a.heap, 0 +#ifdef USE_RUNTIMESTATS + , &a +#endif + ); + ponyint_gc_end_visits(ctx); + ponyint_gc_done(&a.gc); + } +}; +} + +// A mark that reaches B through a pointer into its allocation traces B on the +// first visit and on the first repeat, which is recorded; later visits don't +// trace B, and once the class that starts the allocation is traced, a pointer +// to B needs nothing more. +TEST_F(GcEmbeddedInClass, InteriorVisitsEndAndAreCoveredByTheClass) +{ + A* obj = alloc_a(); + start_mark(); + for(int i = 0; i < 3; i++) + pony_traceknown_routed(ctx, &obj->b, &b_type, PONY_TRACE_MUTABLE); + ponyint_gc_handlestack(ctx); + EXPECT_EQ(2u, b_traced); + EXPECT_EQ(0u, a_traced); + + pony_traceknown(ctx, obj, &a_type, PONY_TRACE_MUTABLE); + ponyint_gc_handlestack(ctx); + EXPECT_EQ(1u, a_traced); + EXPECT_EQ(3u, b_traced); + + pony_traceknown_routed(ctx, &obj->b, &b_type, PONY_TRACE_MUTABLE); + ponyint_gc_handlestack(ctx); + EXPECT_EQ(3u, b_traced); + end_mark(); +} + +// A type embedded in a class shares no address, so it takes the plain trace. +// The plain mark bounds repeat visits through a pointer into the allocation the +// same way: B is traced on the first visit and on the first repeat, which is +// recorded; later visits don't trace B, and once A is traced a pointer to B +// needs nothing more. +TEST_F(GcEmbeddedInClass, PlainInteriorVisitsEnd) +{ + _pony_type_t plain_b = b_type; + plain_b.embed_flags = 0; + A* obj = alloc_a(); + start_mark(); + for(int i = 0; i < 3; i++) + pony_traceknown(ctx, &obj->b, &plain_b, PONY_TRACE_MUTABLE); + ponyint_gc_handlestack(ctx); + EXPECT_EQ(2u, b_traced); + + pony_traceknown(ctx, obj, &a_type, PONY_TRACE_MUTABLE); + pony_traceknown(ctx, &obj->b, &plain_b, PONY_TRACE_MUTABLE); + ponyint_gc_handlestack(ctx); + EXPECT_EQ(1u, a_traced); + EXPECT_EQ(3u, b_traced); + end_mark(); +} + +// An opaque visit to B, as for a tag reference to it, keeps the allocation that +// holds it through the sweep without tracing B. +TEST_F(GcEmbeddedInClass, OpaqueInteriorVisitKeepsTheAllocation) +{ + A* obj = alloc_a(); + start_mark(); + pony_traceknown_routed(ctx, &obj->b, &b_type, PONY_TRACE_OPAQUE); + ponyint_gc_handlestack(ctx); + EXPECT_EQ(0u, b_traced); + end_mark(); + + // Enough allocations of the same size to reuse any freed slot in its chunk. + for(int i = 0; i < 64; i++) + { + void* next = ponyint_heap_alloc(&a, &a.heap, sizeof(A), + TRACK_NO_FINALISERS); + ASSERT_NE(static_cast(obj), next); + } +} + +// Once the class that starts the allocation is traced, a pointer into it to B +// needs nothing more. +TEST_F(GcEmbeddedInClass, InteriorVisitAfterTheClassIsCovered) +{ + A* obj = alloc_a(); + start_mark(); + pony_traceknown(ctx, obj, &a_type, PONY_TRACE_MUTABLE); + ponyint_gc_handlestack(ctx); + EXPECT_EQ(1u, b_traced); + + pony_traceknown_routed(ctx, &obj->b, &b_type, PONY_TRACE_MUTABLE); + ponyint_gc_handlestack(ctx); + EXPECT_EQ(1u, b_traced); + end_mark(); +} + +namespace +{ +void dispatch_nothing(pony_ctx_t* ctx, pony_actor_t* self, pony_msg_t* msg) +{ + (void)ctx; + (void)self; + (void)msg; +} +} + +// Actor descriptors are in the descriptor section, as compiled ones are. +PONY_DESCRIPTOR_SECTION constexpr _pony_type_t small_actor_type = + test_type((uint32_t)(sizeof(pony_actor_t) + 64), nullptr, + dispatch_nothing, PONY_EMBED_ACTOR_LOOKUP); + +// Descriptors in the descriptor section for the pool-memory tests: a type with +// no dispatch function, an actor type without PONY_EMBED_ACTOR_LOOKUP, and a +// 16-byte actor type with it. +PONY_DESCRIPTOR_SECTION constexpr _pony_type_t not_an_actor_type = + test_type(64, nullptr, nullptr, PONY_EMBED_ACTOR_LOOKUP); +// Its size isn't a pool size on 32-bit or 64-bit, so its pool block extends +// past it. +PONY_DESCRIPTOR_SECTION constexpr _pony_type_t plain_actor_type = + test_type((uint32_t)(sizeof(pony_actor_t) + 72), nullptr, + dispatch_nothing, 0); +PONY_DESCRIPTOR_SECTION constexpr _pony_type_t tiny_actor_type = + test_type(16, nullptr, dispatch_nothing, PONY_EMBED_ACTOR_LOOKUP); + +// An actor type whose descriptor isn't in the descriptor section, as when an +// ELF program is linked without ponyc's linker script. +static struct _pony_type_t writable_actor_type = + test_type((uint32_t)(sizeof(pony_actor_t) + 64), nullptr, + dispatch_nothing, PONY_EMBED_ACTOR_LOOKUP); + +// The same bytes as tiny_actor_type, but in the constant section, where a +// string literal or a primitive instance can hold bytes that read as an actor +// descriptor. +PONY_CONSTANT_SECTION constexpr _pony_type_t lookalike_actor_type = + test_type(16, nullptr, dispatch_nothing, PONY_EMBED_ACTOR_LOOKUP); + +// An actor whose block comes from an arena's block class, not a size class. +const size_t block_actor_size = POOL_MAX + POOL_ALIGN; +PONY_DESCRIPTOR_SECTION constexpr _pony_type_t block_actor_type = + test_type((uint32_t)block_actor_size, nullptr, + dispatch_nothing, PONY_EMBED_ACTOR_LOOKUP); + +// Larger than an arena, so the pool gives it a mapping of its own. +const size_t huge_actor_size = 16 * 1024 * 1024; +PONY_DESCRIPTOR_SECTION constexpr _pony_type_t huge_actor_type = + test_type((uint32_t)huge_actor_size, nullptr, + dispatch_nothing, PONY_EMBED_ACTOR_LOOKUP); + +namespace +{ +// The actor whose allocation holds p: the pagemap's actor for an actor +// pony_create recorded there, otherwise ponyint_actor_in_pool's answer. +pony_actor_t* actor_at(void* p) +{ + pony_actor_t* actor = NULL; + + if((ponyint_pagemap_get(p, &actor) == NULL) && (actor != NULL)) + return actor; + + return ponyint_actor_in_pool(p); +} + +// Asserts whether the actor's descriptor is in the descriptor section, and how +// the actor is found from field: by pool lookup when its descriptor is there, +// the arena pool is in use and the actor fits an arena, and from the pagemap +// otherwise. +void assert_lookup_path(pony_actor_t* actor, void* field, bool in_section) +{ + ASSERT_EQ(in_section, ponyint_desc_section_holds(actor->type)); + + bool by_pool = in_section && ponyint_pool_size_in_arena(actor->type->size); + + pony_actor_t* pagemap_actor = nullptr; + ponyint_pagemap_get(field, &pagemap_actor); + ASSERT_EQ(by_pool ? nullptr : actor, pagemap_actor); +} +} + +// An actor is found from the address of one of its fields. +TEST(EmbeddedInActor, FindsTheActorFromAnInteriorAddress) +{ + SKIP_WITHOUT_SECTIONS(); + ponyint_register_thread(); + ponyint_section_bounds_init(); + + pony_actor_t* actor = pony_create(pony_ctx(), &small_actor_type, true); + char* field = reinterpret_cast(actor) + sizeof(pony_actor_t) + 8; + ASSERT_NO_FATAL_FAILURE( + assert_lookup_path(actor, field, /*in_section=*/true)); + EXPECT_EQ(actor, actor_at(field)); + + uint64_t local = 0; + EXPECT_EQ(nullptr, actor_at(&local)); + + ponyint_destroy(actor); + ponyint_unregister_thread(); +} + +namespace +{ +// A field embedded in an actor is traced by the call compiled code uses for its +// type: a type that can share an address with an object of another type is +// routed. +void trace_field(pony_ctx_t* ctx, void* field, pony_type_t* t, bool routed) +{ + if(routed) + pony_traceknown_routed(ctx, field, t, PONY_TRACE_MUTABLE); + else + pony_traceknown(ctx, field, t, PONY_TRACE_MUTABLE); +} +} + +// An actor that marks a field embedded in another actor adds the field's size +// to its own heap use, as it adds a heap object's size. +TEST(EmbeddedInActor, RemoteMarkOfAnEmbeddedFieldCountsItsSize) +{ + SKIP_WITHOUT_SECTIONS(); + // The owner is found by pool lookup, or from the pagemap for an actor whose + // descriptor isn't in the descriptor section (and, with the memalign pool, + // for every actor). + for(const _pony_type_t* owner_type : {&small_actor_type, + static_cast(&writable_actor_type)}) + for(bool routed : {false, true}) + { + SCOPED_TRACE(routed ? "routed" : "plain"); + SCOPED_TRACE(owner_type == &small_actor_type ? "small_actor_type" : + "writable_actor_type"); + ponyint_register_thread(); + ponyint_section_bounds_init(); + pony_ctx_t* ctx = pony_ctx(); + + pony_actor_t* owner = pony_create(ctx, owner_type, true); + char* field = reinterpret_cast(owner) + sizeof(pony_actor_t) + 8; + ASSERT_NO_FATAL_FAILURE( + assert_lookup_path(owner, field, + /*in_section=*/owner_type == &small_actor_type)); + _pony_type_t field_type{}; + field_type.size = 24; + field_type.embed_flags = PONY_EMBED_IN_ACTOR | + (routed ? PONY_EMBED_ROUTED : 0); + + pony_actor_t holder{}; + _pony_type_t holder_type{}; + holder.type = &holder_type; + ponyint_heap_init(&holder.heap); + ponyint_gc_done(&holder.gc); + ctx->current = &holder; + + ponyint_gc_mark(ctx); + // Marking the owner charges for the actor; measure the field alone. + ponyint_gc_markactor(ctx, owner); + size_t before = holder.heap.used; + trace_field(ctx, field, &field_type, routed); + ponyint_gc_handlestack(ctx); + EXPECT_EQ(before + field_type.size, holder.heap.used); + + ponyint_actormap_destroy(&ctx->acquire); + ponyint_gc_done(&holder.gc); + ctx->current = NULL; + ponyint_gc_destroy(&holder.gc); + ponyint_heap_destroy(&holder.heap); + ponyint_destroy(owner); + ponyint_unregister_thread(); + } +} + +// An actor that receives a field embedded in another actor adds the field's +// size to its own heap use. +TEST(EmbeddedInActor, ReceiveOfAnEmbeddedFieldCountsItsSize) +{ + SKIP_WITHOUT_SECTIONS(); + // The owner is found by pool lookup, or from the pagemap for an actor whose + // descriptor isn't in the descriptor section (and, with the memalign pool, + // for every actor). + for(const _pony_type_t* owner_type : {&small_actor_type, + static_cast(&writable_actor_type)}) + for(bool routed : {false, true}) + { + SCOPED_TRACE(routed ? "routed" : "plain"); + SCOPED_TRACE(owner_type == &small_actor_type ? "small_actor_type" : + "writable_actor_type"); + ponyint_register_thread(); + ponyint_section_bounds_init(); + pony_ctx_t* ctx = pony_ctx(); + + pony_actor_t* owner = pony_create(ctx, owner_type, true); + char* field = reinterpret_cast(owner) + sizeof(pony_actor_t) + 8; + ASSERT_NO_FATAL_FAILURE( + assert_lookup_path(owner, field, + /*in_section=*/owner_type == &small_actor_type)); + _pony_type_t field_type{}; + field_type.size = 24; + field_type.embed_flags = PONY_EMBED_IN_ACTOR | + (routed ? PONY_EMBED_ROUTED : 0); + + pony_actor_t holder{}; + _pony_type_t holder_type{}; + holder.type = &holder_type; + ponyint_heap_init(&holder.heap); + ponyint_gc_done(&holder.gc); + ctx->current = &holder; + + pony_gc_recv(ctx); + // Receiving the owner charges for the actor; measure the field alone. + ponyint_gc_recvactor(ctx, owner); + size_t before = holder.heap.used; + trace_field(ctx, field, &field_type, routed); + ponyint_gc_handlestack(ctx); + EXPECT_EQ(before + field_type.size, holder.heap.used); + + ponyint_gc_end_visits(ctx); + ponyint_actormap_destroy(&ctx->acquire); + ponyint_gc_done(&holder.gc); + ctx->current = NULL; + ponyint_gc_destroy(&holder.gc); + ponyint_heap_destroy(&holder.heap); + ponyint_destroy(owner); + ponyint_unregister_thread(); + } +} + +namespace +{ +size_t own_field_traced; + +void trace_own_field(pony_ctx_t* ctx, void* p) +{ + (void)ctx; + (void)p; + own_field_traced++; +} + +void end_own_epoch(pony_ctx_t* ctx, pony_actor_t* actor) +{ + ponyint_gc_end_visits(ctx); + ponyint_actormap_destroy(&ctx->acquire); + ponyint_gc_done(&actor->gc); + ctx->msg_target = NULL; +} +} + +// An actor that sends a field embedded in itself, and gets it back, counts it +// as its own object: the counts return to where they started, and it never +// holds or acquires itself. Its own mark leaves the field to its own trace. +TEST(EmbeddedInActor, OwnEmbeddedFieldIsALocalObject) +{ + for(bool routed : {false, true}) + { + SCOPED_TRACE(routed ? "routed" : "plain"); + ponyint_register_thread(); + ponyint_section_bounds_init(); + pony_ctx_t* ctx = pony_ctx(); + + pony_actor_t* owner = pony_create(ctx, &small_actor_type, true); + char* field = reinterpret_cast(owner) + sizeof(pony_actor_t) + 8; + _pony_type_t field_type{}; + field_type.size = 24; + field_type.trace = trace_own_field; + field_type.embed_flags = PONY_EMBED_IN_ACTOR | + (routed ? PONY_EMBED_ROUTED : 0); + pony_actor_t target{}; + ctx->current = owner; + size_t rc_before = owner->gc.rc; + size_t index = HASHMAP_UNKNOWN; + + pony_gc_send(ctx, &target); + trace_field(ctx, field, &field_type, routed); + ponyint_gc_handlestack(ctx); + object_t* obj = ponyint_objectmap_getobject(&owner->gc.local, field, + &index); + ASSERT_NE(nullptr, obj); + EXPECT_EQ(1u, obj->rc); + EXPECT_EQ(rc_before + 1, owner->gc.rc); + EXPECT_EQ(0u, ponyint_actormap_size(&owner->gc.foreign)); + EXPECT_EQ(0u, ponyint_actormap_size(&ctx->acquire)); + end_own_epoch(ctx, owner); + + pony_gc_recv(ctx); + trace_field(ctx, field, &field_type, routed); + ponyint_gc_handlestack(ctx); + EXPECT_EQ(0u, obj->rc); + EXPECT_EQ(rc_before, owner->gc.rc); + EXPECT_EQ(0u, ponyint_actormap_size(&owner->gc.foreign)); + end_own_epoch(ctx, owner); + + own_field_traced = 0; + ponyint_gc_mark(ctx); + trace_field(ctx, field, &field_type, routed); + ponyint_gc_handlestack(ctx); + EXPECT_EQ(0u, own_field_traced); + EXPECT_EQ(0u, ponyint_actormap_size(&owner->gc.foreign)); + EXPECT_EQ(0u, ponyint_actormap_size(&ctx->acquire)); + end_own_epoch(ctx, owner); + + ctx->current = NULL; + ponyint_destroy(owner); + ponyint_unregister_thread(); + } +} + +// Memory just past the current actor, inside the pool block that holds it, is +// not one of the actor's fields: a visit there is traced as memory no actor +// owns. +TEST(EmbeddedInActor, AddressPastTheCurrentActorIsNotItsField) +{ + ponyint_register_thread(); + ponyint_section_bounds_init(); + pony_ctx_t* ctx = pony_ctx(); + + // Without PONY_EMBED_ACTOR_LOOKUP, so no pool lookup or pagemap entry finds + // the actor from the address past it. + pony_actor_t* owner = pony_create(ctx, &plain_actor_type, true); + ASSERT_GT(ponyint_pool_used_size(plain_actor_type.size), + (size_t)plain_actor_type.size); + char* past = reinterpret_cast(owner) + plain_actor_type.size; + _pony_type_t field_type{}; + field_type.size = 8; + field_type.trace = trace_own_field; + field_type.embed_flags = PONY_EMBED_IN_ACTOR; + ctx->current = owner; + + own_field_traced = 0; + ponyint_gc_mark(ctx); + pony_traceknown(ctx, past, &field_type, PONY_TRACE_MUTABLE); + ponyint_gc_handlestack(ctx); + EXPECT_EQ(1u, own_field_traced); + end_own_epoch(ctx, owner); + + ctx->current = NULL; + ponyint_destroy(owner); + ponyint_unregister_thread(); +} + +#ifdef POOL_USE_ARENA +// A destroyed actor's freed block, taken from the pool again as plain memory, +// isn't taken for that actor. The arena pool hands a freed block back for the +// next allocation of its size; the memalign pool need not. +TEST(EmbeddedInActor, DestroyedActorsBlockIsNotAnActor) +{ +#if !defined(PONY_NDEBUG) || defined(PONY_ALWAYS_ASSERT) + GTEST_SKIP() << "the debug pool overwrites a freed block's first word"; +#endif + SKIP_WITHOUT_SECTIONS(); + ponyint_register_thread(); + ponyint_section_bounds_init(); + pony_ctx_t* ctx = pony_ctx(); + + for(const _pony_type_t* t : {&small_actor_type, &block_actor_type}) + { + SCOPED_TRACE(t->size); + ASSERT_TRUE(ponyint_pool_size_in_arena(t->size)); + + pony_actor_t* actor = pony_create(ctx, t, true); + char* field = reinterpret_cast(actor) + sizeof(pony_actor_t) + 8; + ASSERT_NO_FATAL_FAILURE( + assert_lookup_path(actor, field, /*in_section=*/true)); + ASSERT_EQ(actor, actor_at(field)); + ponyint_destroy(actor); + + // The pool hands the block that was just freed back for the same size. + void* block = ponyint_pool_alloc_size(t->size); + ASSERT_EQ(static_cast(actor), block); + EXPECT_EQ(nullptr, actor_at(field)); + + ponyint_pool_free_size(t->size, block); + } + + ponyint_unregister_thread(); +} +#endif + +// An actor too large for an arena is found too. +TEST(EmbeddedInActor, FindsAnActorTooLargeForAnArena) +{ + ponyint_register_thread(); + ponyint_section_bounds_init(); + ASSERT_FALSE(ponyint_pool_size_in_arena(huge_actor_size)); + + pony_actor_t* actor = pony_create(pony_ctx(), &huge_actor_type, true); + char* field = reinterpret_cast(actor) + huge_actor_size - 8; + EXPECT_EQ(actor, actor_at(field)); + + ponyint_destroy(actor); + EXPECT_EQ(nullptr, actor_at(field)); + ponyint_unregister_thread(); +} + +// An actor whose descriptor isn't in the descriptor section is found through +// the pagemap, which forgets it when it is destroyed. +TEST(EmbeddedInActor, FindsAnActorWhoseTypeIsNotInTheDescriptorSection) +{ + ponyint_register_thread(); + ponyint_section_bounds_init(); + ASSERT_FALSE(ponyint_desc_section_holds(&writable_actor_type)); + + pony_actor_t* actor = pony_create(pony_ctx(), &writable_actor_type, true); + char* field = reinterpret_cast(actor) + sizeof(pony_actor_t) + 8; + EXPECT_EQ(actor, actor_at(field)); + + ponyint_destroy(actor); + + pony_actor_t* pagemap_actor = nullptr; + EXPECT_EQ(nullptr, ponyint_pagemap_get(field, &pagemap_actor)); + EXPECT_EQ(nullptr, pagemap_actor); + ponyint_unregister_thread(); +} + +// An actor recorded in the pagemap has its pagemap entries to itself: pool +// blocks of the actor type's size and of POOL_ALIGN bytes, allocated before and +// after it, aren't taken for it. POOL_ALIGN bytes is the size the pool gives +// the actor, so the POOL_ALIGN blocks come from the actor's size class. +TEST(EmbeddedInActor, PagemapActorSharesNoEntry) +{ + ASSERT_LT(writable_actor_type.size, POOL_ALIGN); + ponyint_register_thread(); + ponyint_section_bounds_init(); + + const size_t sizes[2] = {writable_actor_type.size, POOL_ALIGN}; + char* blocks[2][8]; + for(size_t s = 0; s < 2; s++) + for(size_t i = 0; i < 4; i++) + blocks[s][i] = static_cast(ponyint_pool_alloc_size(sizes[s])); + pony_actor_t* actor = pony_create(pony_ctx(), &writable_actor_type, true); + for(size_t s = 0; s < 2; s++) + for(size_t i = 4; i < 8; i++) + blocks[s][i] = static_cast(ponyint_pool_alloc_size(sizes[s])); + + // The actor starts on a pagemap entry, and the entry after it isn't the + // actor's: an actor recorded in too many entries spills into that one. + EXPECT_EQ(0u, reinterpret_cast(actor) % POOL_ALIGN); + pony_actor_t* next = nullptr; + ponyint_pagemap_get(reinterpret_cast(actor) + POOL_ALIGN, &next); + EXPECT_NE(actor, next); + + for(size_t s = 0; s < 2; s++) + { + for(size_t i = 0; i < 8; i++) + { + SCOPED_TRACE(sizes[s]); + SCOPED_TRACE(i); + memset(blocks[s][i], 0, sizes[s]); + EXPECT_EQ(nullptr, actor_at(blocks[s][i] + 8)); + } + } + + ponyint_destroy(actor); + for(size_t s = 0; s < 2; s++) + for(size_t i = 0; i < 8; i++) + ponyint_pool_free_size(sizes[s], blocks[s][i]); + ponyint_unregister_thread(); +} + +// An actor type whose actors are recorded in the pagemap. Its size covers three +// pagemap entries, and the pool rounds it up to a block that covers four. +static struct _pony_type_t multi_entry_actor_type = + test_type((uint32_t)(2 * POOL_ALIGN + 52), nullptr, dispatch_nothing, + PONY_EMBED_ACTOR_LOOKUP); + +// An actor recorded in the pagemap is recorded in every entry of its pool +// block, and destroying it forgets every one of them. +TEST(EmbeddedInActor, PagemapActorIsForgottenAcrossItsWholeBlock) +{ + ponyint_register_thread(); + ponyint_section_bounds_init(); + ASSERT_FALSE(ponyint_desc_section_holds(&multi_entry_actor_type)); + + size_t block = ponyint_pool_used_size(multi_entry_actor_type.size); + size_t size_entries = + (multi_entry_actor_type.size + POOL_ALIGN - 1) / POOL_ALIGN; + ASSERT_GT(block / POOL_ALIGN, size_entries); + + pony_actor_t* actor = pony_create(pony_ctx(), &multi_entry_actor_type, + true); + char* base = reinterpret_cast(actor); + + for(size_t offset = 0; offset < block; offset += POOL_ALIGN) + { + SCOPED_TRACE(offset); + pony_actor_t* pagemap_actor = nullptr; + ponyint_pagemap_get(base + offset, &pagemap_actor); + EXPECT_EQ(actor, pagemap_actor); + } + + ponyint_destroy(actor); + + for(size_t offset = 0; offset < block; offset += POOL_ALIGN) + { + SCOPED_TRACE(offset); + pony_actor_t* pagemap_actor = nullptr; + ponyint_pagemap_get(base + offset, &pagemap_actor); + EXPECT_NE(actor, pagemap_actor); + } + + ponyint_unregister_thread(); +} + +#ifdef USE_RUNTIMESTATS +// An actor recorded in the pagemap is counted at the size the pool gives it, +// the same when it is created and when it is destroyed. +TEST(EmbeddedInActor, PagemapActorIsCountedAtItsAllocationSize) +{ + ASSERT_LT(writable_actor_type.size, POOL_ALIGN); + ponyint_register_thread(); + ponyint_section_bounds_init(); + pony_ctx_t* ctx = pony_ctx(); + + int64_t before = ctx->schedulerstats.mem_allocated_actors; + pony_actor_t* actor = pony_create(ctx, &writable_actor_type, true); + size_t size = ponyint_pool_used_size(POOL_ALIGN); + EXPECT_EQ(size, ponyint_actor_alloc_size(actor)); + EXPECT_EQ(before + (int64_t)size, ctx->schedulerstats.mem_allocated_actors); + + ponyint_destroy(actor); + EXPECT_EQ(before, ctx->schedulerstats.mem_allocated_actors); + ponyint_unregister_thread(); +} +#endif + +namespace +{ +// Restores the descriptor section's bounds when a test that changes them ends, +// however it ends. +struct SavedDescriptorBounds +{ + uintptr_t start = ponyint_desc_section_start; + uintptr_t end = ponyint_desc_section_end; + + ~SavedDescriptorBounds() + { + ponyint_desc_section_start = start; + ponyint_desc_section_end = end; + } +}; +} + +// When the descriptor section ends inside an actor type's descriptor, actors of +// that type are still found from their embedded fields: creation and lookup +// agree that the descriptor isn't in the section. +TEST(EmbeddedInActor, DescriptorPartlyInTheDescriptorSection) +{ + ponyint_register_thread(); + ponyint_section_bounds_init(); + SavedDescriptorBounds saved; + // The actor is created and destroyed under the same bounds, as sections.h + // requires. + ponyint_desc_section_start = (uintptr_t)&small_actor_type; + ponyint_desc_section_end = + (uintptr_t)&small_actor_type + (sizeof(_pony_type_t) / 2); + + pony_actor_t* actor = pony_create(pony_ctx(), &small_actor_type, true); + char* field = reinterpret_cast(actor) + sizeof(pony_actor_t) + 8; + EXPECT_EQ(actor, actor_at(field)); + ponyint_destroy(actor); + ponyint_unregister_thread(); +} + +// Pool memory handed to Pony through FFI isn't taken for an actor unless its +// first word is an actor descriptor in the descriptor section whose type has +// PONY_EMBED_ACTOR_LOOKUP and whose size reaches the address. +TEST(EmbeddedInActor, PoolMemoryThatIsNotAnActor) +{ + SKIP_WITHOUT_SECTIONS(); + ponyint_register_thread(); + ponyint_section_bounds_init(); + + size_t size = sizeof(pony_actor_t) + 64; + char* block = static_cast(ponyint_pool_alloc_size(size)); + memset(block, 0, size); + EXPECT_EQ(nullptr, actor_at(block + 16)); + + // A first word in the descriptor section that isn't an actor descriptor. + *reinterpret_cast(block) = ¬_an_actor_type; + EXPECT_EQ(nullptr, actor_at(block + 16)); + + // An actor descriptor for a type with no embedded field. + *reinterpret_cast(block) = &plain_actor_type; + EXPECT_EQ(nullptr, actor_at(block + 16)); + + // An actor descriptor, but the address is past that actor's size. + *reinterpret_cast(block) = &tiny_actor_type; + EXPECT_EQ(nullptr, actor_at(block + 16)); +#ifdef POOL_USE_ARENA + // In the arena pool, ponyint_pool_base finds the allocation's start, and + // ponyint_actor_in_pool takes it for an actor by its descriptor. The + // memalign pool has no lookup, so its actors are recorded in the pagemap. + EXPECT_EQ(reinterpret_cast(block), + ponyint_actor_in_pool(block + 8)); + + // Bytes that read as an actor descriptor, in the constant section rather + // than the descriptor section, as a string literal or a primitive instance + // can. + *reinterpret_cast(block) = &lookalike_actor_type; + EXPECT_EQ(nullptr, ponyint_actor_in_pool(block + 8)); + + { + SavedDescriptorBounds saved; + + // A descriptor that ends exactly where the descriptor section ends. + *reinterpret_cast(block) = &tiny_actor_type; + ponyint_desc_section_start = (uintptr_t)&tiny_actor_type; + ponyint_desc_section_end = + (uintptr_t)&tiny_actor_type + sizeof(_pony_type_t); + EXPECT_EQ(reinterpret_cast(block), + ponyint_actor_in_pool(block + 8)); + + // A descriptor that starts in the descriptor section but ends past it. + ponyint_desc_section_end = + (uintptr_t)&tiny_actor_type + sizeof(_pony_type_t) - 1; + EXPECT_EQ(nullptr, actor_at(block + 8)); + + // A descriptor that starts before the descriptor section and ends in it. + ponyint_desc_section_start = (uintptr_t)&tiny_actor_type + 8; + ponyint_desc_section_end = + (uintptr_t)&tiny_actor_type + sizeof(_pony_type_t); + EXPECT_EQ(nullptr, actor_at(block + 8)); + + // A descriptor in the descriptor section that isn't aligned: a copy of an + // actor descriptor one byte into a buffer. + alignas(16) static char misaligned[sizeof(_pony_type_t) + 1]; + memcpy(misaligned + 1, &tiny_actor_type, sizeof(_pony_type_t)); + ponyint_desc_section_start = (uintptr_t)misaligned; + ponyint_desc_section_end = (uintptr_t)misaligned + sizeof(misaligned); + *reinterpret_cast(block) = misaligned + 1; + EXPECT_EQ(nullptr, actor_at(block + 8)); + } +#endif + + ponyint_pool_free_size(size, block); + ponyint_unregister_thread(); +} diff --git a/test/libponyrt/gc/marklocal.cc b/test/libponyrt/gc/marklocal.cc index 81aaee9d41e..14f8f3f9b26 100644 --- a/test/libponyrt/gc/marklocal.cc +++ b/test/libponyrt/gc/marklocal.cc @@ -1,11 +1,16 @@ #include #include +#include +#include #include #include #include #include #include + +#include "test_type.h" +#include "test_sections.h" #ifdef PLATFORM_IS_WINDOWS # include #endif @@ -35,6 +40,23 @@ void trace_frame(pony_ctx_t* ctx, void* p) pony_traceunknown(ctx, p, PONY_TRACE_MUTABLE); } +size_t counted_traces = 0; + +void trace_counted(pony_ctx_t* ctx, void* p) +{ + (void)ctx; + (void)p; + counted_traces++; +} + +const _pony_type_t counted_type = + test_type(sizeof(Node), trace_counted, nullptr, 0); +const _pony_type_t counted_routed_type = + test_type(sizeof(Node), trace_counted, nullptr, PONY_EMBED_ROUTED); +PONY_CONSTANT_SECTION const Node constant_node = {&counted_type, nullptr}; +Node writable_node = {&counted_type, nullptr}; +Node writable_routed_node = {&counted_routed_type, nullptr}; + class LocalGc : public testing::Test { protected: @@ -353,6 +375,43 @@ TEST_F(LocalGc, IndexedUnwindRefusesThenCollectsThroughSupportedSite) } #endif +// A mark inside a behaviour doesn't trace an object in the constant section, +// and does trace a writable object outside every heap. +TEST_F(LocalGc, ConstantsAreNotTraced) +{ + SKIP_WITHOUT_SECTIONS(); + ponyint_section_bounds_init(); + ASSERT_TRUE(ponyint_in_const_section(&constant_node)); + ASSERT_FALSE(ponyint_in_const_section(&writable_node)); + node(); + counted_traces = 0; + + actor.heap.next_gc = 0; + pony_ctx_t* marking = ponyint_gc_poll(ctx, nullptr); + ASSERT_NE(nullptr, marking); + pony_traceknown(marking, const_cast(&constant_node), &counted_type, + PONY_TRACE_MUTABLE); + pony_traceknown(marking, &writable_node, &counted_type, PONY_TRACE_MUTABLE); + ASSERT_TRUE(ponyint_gc_finish(marking)); + EXPECT_EQ(1u, counted_traces); +} + +// A mark inside a behaviour takes routed traces too: a writable routed object +// outside every heap is traced. +TEST_F(LocalGc, RoutedObjectOutsideHeapsIsTraced) +{ + node(); + counted_traces = 0; + + actor.heap.next_gc = 0; + pony_ctx_t* marking = ponyint_gc_poll(ctx, nullptr); + ASSERT_NE(nullptr, marking); + pony_traceknown_routed(marking, &writable_routed_node, &counted_routed_type, + PONY_TRACE_MUTABLE); + ASSERT_TRUE(ponyint_gc_finish(marking)); + EXPECT_EQ(1u, counted_traces); +} + TEST_F(LocalGc, ShallowAndReadableNeighboursHaveIndependentChildren) { Node* opaque = node(); @@ -654,8 +713,8 @@ TEST_P(FinaliserBoundary, MarkKeepsOnlyReadableFinalisersEligible) ); if(readable) { - ponyint_heap_mark(chunk_of(resource), resource); - ponyint_heap_mark(chunk_of(resource->child), resource->child); + ponyint_heap_mark_plain(chunk_of(resource), resource); + ponyint_heap_mark_plain(chunk_of(resource->child), resource->child); } else { mark_held_elsewhere(resource); } @@ -682,8 +741,8 @@ TEST_P(FinaliserBoundary, DeepMarkMakesAnUnreportedFinaliserEligible) , &actor #endif ); - ponyint_heap_mark(chunk_of(resource), resource); - ponyint_heap_mark(chunk_of(resource->child), resource->child); + ponyint_heap_mark_plain(chunk_of(resource), resource); + ponyint_heap_mark_plain(chunk_of(resource->child), resource->child); ponyint_heap_endgc(&actor.heap, 0 #ifdef USE_RUNTIMESTATS , &actor @@ -747,7 +806,7 @@ TEST_P(FinaliserBoundary, InteriorMarkLeavesAFinaliserUntraceable) , &actor #endif ); - ponyint_heap_mark(chunk_of(resource), &resource->child); + ponyint_heap_mark_plain(chunk_of(resource), &resource->child); ponyint_heap_mark_shallow(chunk_of(resource->child), resource->child); ponyint_heap_endgc(&actor.heap, 0 #ifdef USE_RUNTIMESTATS diff --git a/test/libponyrt/gc/sections.cc b/test/libponyrt/gc/sections.cc new file mode 100644 index 00000000000..ce7e714d36e --- /dev/null +++ b/test/libponyrt/gc/sections.cc @@ -0,0 +1,218 @@ +#include + +#include +#include +#include +#include +#include +#include +#include + +#include + +#include "test_type.h" +#include "test_sections.h" +#include +#include + +// The GC skips objects in the compiler's constant section, so nothing there may +// be written at run time. + +namespace +{ +PONY_CONSTANT_SECTION const uint64_t constant_value = 7; + +// A constant holding a pointer, which the loader must relocate. +PONY_CONSTANT_SECTION const uint64_t* const constant_pointer = &constant_value; + +// Read-only, but not in the constant section. +const uint64_t outside_constant = 7; + +// Relocated in position-independent code, so on ELF it sits in .data.rel.ro, +// after both sections. +const uint64_t* const outside_pointer = &outside_constant; + +uint64_t writable_value = 7; +uint64_t zeroed_value; +} + +TEST(Sections, ConstantSectionObjectsAreConstants) +{ + SKIP_WITHOUT_SECTIONS(); + ponyint_section_bounds_init(); + + ASSERT_TRUE(ponyint_in_const_section(&constant_value)); + ASSERT_TRUE(ponyint_in_const_section(&constant_pointer)); +} + +namespace +{ +PONY_DESCRIPTOR_SECTION constexpr _pony_type_t descriptor_in_section = + test_type(64, nullptr, nullptr, 0); +} + +// Descriptors and the other constants are in separate ranges, so no constant +// can be taken for a descriptor. +TEST(Sections, DescriptorsAreApartFromOtherConstants) +{ + SKIP_WITHOUT_SECTIONS(); + ponyint_section_bounds_init(); + + ASSERT_TRUE(ponyint_desc_section_holds(&descriptor_in_section)); + ASSERT_FALSE(ponyint_in_const_section(&descriptor_in_section)); + ASSERT_FALSE(ponyint_desc_section_holds( + reinterpret_cast(&constant_value))); +} + +TEST(Sections, OtherMemoryIsNotConstant) +{ + ponyint_section_bounds_init(); + + uint64_t local = 7; + void* heap = malloc(64); + + ASSERT_FALSE(ponyint_in_const_section(&outside_constant)); + ASSERT_FALSE(ponyint_in_const_section(&outside_pointer)); + ASSERT_FALSE(ponyint_in_const_section(&writable_value)); + ASSERT_FALSE(ponyint_in_const_section(&zeroed_value)); + ASSERT_FALSE(ponyint_in_const_section(&local)); + ASSERT_FALSE(ponyint_in_const_section(heap)); + + free(heap); +} + +namespace +{ +size_t constant_traced; + +void trace_counted(pony_ctx_t* ctx, void* p) +{ + (void)ctx; + (void)p; + constant_traced++; +} + +struct Object +{ + const _pony_type_t* type; + uint64_t x; +}; + +const _pony_type_t counted_type = + test_type(sizeof(Object), trace_counted, nullptr, 0); +const _pony_type_t counted_routed_type = + test_type(sizeof(Object), trace_counted, nullptr, PONY_EMBED_ROUTED); + +PONY_CONSTANT_SECTION const Object constant_object = {&counted_type, 1}; +PONY_CONSTANT_SECTION const Object constant_routed_object = + {&counted_routed_type, 1}; +Object writable_object = {&counted_type, 1}; +Object writable_routed_object = {&counted_routed_type, 1}; +} + +// A raw trace (pony_trace) has no type. When its memory has no heap chunk, as +// for memory from C, a send, receive or mark leaves it alone. +TEST(Sections, RawTraceOfMemoryOutsideTheHeap) +{ + ponyint_register_thread(); + ponyint_section_bounds_init(); + pony_ctx_t* ctx = pony_ctx(); + _pony_type_t actor_type{}; + pony_actor_t actor{}; + actor.type = &actor_type; + ponyint_heap_init(&actor.heap); + ponyint_gc_done(&actor.gc); + ctx->current = &actor; + void* from_c = malloc(64); + + for(const char* mode : {"mark", "send", "receive"}) + { + SCOPED_TRACE(mode); + + if(strcmp(mode, "send") == 0) + pony_gc_send(ctx, &actor); + else if(strcmp(mode, "receive") == 0) + pony_gc_recv(ctx); + else + ponyint_gc_mark(ctx); + + pony_trace(ctx, from_c); + pony_trace(ctx, nullptr); + ponyint_gc_handlestack(ctx); + size_t index = HASHMAP_UNKNOWN; + EXPECT_EQ(nullptr, + ponyint_objectmap_getobject(&actor.gc.local, from_c, &index)); + EXPECT_EQ(0u, ponyint_actormap_size(&ctx->acquire)); + EXPECT_EQ(0u, ponyint_actormap_size(&actor.gc.foreign)); + + ponyint_gc_end_visits(ctx); + ponyint_actormap_destroy(&ctx->acquire); + ponyint_gc_done(&actor.gc); + ctx->msg_target = NULL; + } + + free(from_c); + ctx->current = NULL; + ponyint_gc_destroy(&actor.gc); + ponyint_heap_destroy(&actor.heap); + ponyint_unregister_thread(); +} + +// A send, receive or mark doesn't trace an object in the constant section, on +// the plain or the routed path; a writable object outside every heap is traced, +// unless the visit is opaque. +TEST(Sections, GcDoesNotTraceConstants) +{ + SKIP_WITHOUT_SECTIONS(); + ponyint_register_thread(); + ponyint_section_bounds_init(); + pony_ctx_t* ctx = pony_ctx(); + _pony_type_t actor_type{}; + pony_actor_t actor{}; + actor.type = &actor_type; + ponyint_heap_init(&actor.heap); + ponyint_gc_done(&actor.gc); + ctx->current = &actor; + + for(const char* mode : {"mark", "send", "receive"}) + { + SCOPED_TRACE(mode); + constant_traced = 0; + + if(strcmp(mode, "send") == 0) + pony_gc_send(ctx, &actor); + else if(strcmp(mode, "receive") == 0) + pony_gc_recv(ctx); + else + ponyint_gc_mark(ctx); + + pony_traceknown(ctx, const_cast(&constant_object), + &counted_type, PONY_TRACE_MUTABLE); + pony_traceknown_routed(ctx, const_cast(&constant_routed_object), + &counted_routed_type, PONY_TRACE_MUTABLE); + ponyint_gc_handlestack(ctx); + EXPECT_EQ(0u, constant_traced); + + pony_traceknown(ctx, &writable_object, &counted_type, PONY_TRACE_OPAQUE); + pony_traceknown_routed(ctx, &writable_routed_object, &counted_routed_type, + PONY_TRACE_OPAQUE); + ponyint_gc_handlestack(ctx); + EXPECT_EQ(0u, constant_traced); + + pony_traceknown(ctx, &writable_object, &counted_type, PONY_TRACE_MUTABLE); + pony_traceknown_routed(ctx, &writable_routed_object, &counted_routed_type, + PONY_TRACE_MUTABLE); + ponyint_gc_handlestack(ctx); + EXPECT_EQ(2u, constant_traced); + + ponyint_gc_end_visits(ctx); + ponyint_actormap_destroy(&ctx->acquire); + ponyint_gc_done(&actor.gc); + ctx->msg_target = NULL; + } + + ctx->current = NULL; + ponyint_gc_destroy(&actor.gc); + ponyint_heap_destroy(&actor.heap); + ponyint_unregister_thread(); +} diff --git a/test/libponyrt/gc/test_sections.h b/test/libponyrt/gc/test_sections.h new file mode 100644 index 00000000000..dc8629904df --- /dev/null +++ b/test/libponyrt/gc/test_sections.h @@ -0,0 +1,17 @@ +#ifndef TEST_LIBPONYRT_GC_TEST_SECTIONS_H +#define TEST_LIBPONYRT_GC_TEST_SECTIONS_H + +#include + +// Skips a test that needs the descriptor and constant sections when the build +// linked the test binary without ponyc's linker script, because the linker +// can't use it (test/libponyrt/CMakeLists.txt). In every other build, the test +// runs and checks the sections. +#ifdef PONY_TESTS_WITHOUT_SECTIONS_SCRIPT +# define SKIP_WITHOUT_SECTIONS() \ + GTEST_SKIP() << "linked without ponyc's linker script" +#else +# define SKIP_WITHOUT_SECTIONS() ((void)0) +#endif + +#endif diff --git a/test/libponyrt/gc/test_type.h b/test/libponyrt/gc/test_type.h new file mode 100644 index 00000000000..3d75b5f5861 --- /dev/null +++ b/test/libponyrt/gc/test_type.h @@ -0,0 +1,20 @@ +#ifndef TEST_LIBPONYRT_GC_TEST_TYPE_H +#define TEST_LIBPONYRT_GC_TEST_TYPE_H + +#include + +// A type descriptor for a runtime test. Every field not named here is 0 or +// NULL, except might_reference_actor, which is true as in compiled code. +constexpr _pony_type_t test_type(uint32_t size, pony_trace_fn trace, + pony_dispatch_fn dispatch, uint8_t embed_flags) +{ + _pony_type_t t{}; + t.size = size; + t.trace = trace; + t.dispatch = dispatch; + t.might_reference_actor = true; + t.embed_flags = embed_flags; + return t; +} + +#endif diff --git a/test/libponyrt/mem/heap.cc b/test/libponyrt/mem/heap.cc index e48e2371d86..f2d4763343f 100644 --- a/test/libponyrt/mem/heap.cc +++ b/test/libponyrt/mem/heap.cc @@ -60,7 +60,7 @@ TEST(Heap, Init) ); #endif - ponyint_heap_mark(chunk, p); + ponyint_heap_mark_plain(chunk, p); ponyint_heap_endgc(&heap, 0 #ifdef USE_RUNTIMESTATS diff --git a/test/libponyrt/mem/pool.cc b/test/libponyrt/mem/pool.cc index 4014a24ba29..b3f0f653066 100644 --- a/test/libponyrt/mem/pool.cc +++ b/test/libponyrt/mem/pool.cc @@ -4029,3 +4029,106 @@ TEST(PoolArenaDeath, RegionReservationExhaustion) #endif #endif + +#ifdef POOL_USE_ARENA +// Any address inside a live allocation in an arena leads back to the start of +// that allocation, for every kind of slab: several objects per unit, one +// object spanning several units, and a block span. An allocation too large +// for an arena has a mapping of its own, which isn't looked up. +TEST(Pool, BaseFromInteriorAddress) +{ + ASSERT_TRUE(ponyint_pool_size_in_arena(POOL_MAX + 1)); + + // Sizes that are and aren't a size class's own size, so a block can be + // larger than the request. + for(size_t size : {(size_t)32, (size_t)33, (size_t)48, (size_t)100, + (size_t)384, (size_t)512, (size_t)1024, (size_t)3000, (size_t)16384, + (size_t)65536, (size_t)70000, (size_t)POOL_MAX + 1, (size_t)POOL_MAX * 2}) + { + SCOPED_TRACE(size); + size_t used = ponyint_pool_used_size(size); + // Several objects, so that most don't start their slab. + char* p[4]; + for(size_t i = 0; i < 4; i++) + p[i] = static_cast(ponyint_pool_alloc_size(size)); + for(size_t i = 0; i < 4; i++) + { + char* base = ponyint_pool_size_in_arena(size) ? p[i] : nullptr; + EXPECT_EQ(base, ponyint_pool_base(p[i])); + EXPECT_EQ(base, ponyint_pool_base(p[i] + 1)); + EXPECT_EQ(base, ponyint_pool_base(p[i] + (size / 2))); + EXPECT_EQ(base, ponyint_pool_base(p[i] + size - 1)); + EXPECT_EQ(base, ponyint_pool_base(p[i] + used - 1)); + } + for(size_t i = 0; i < 4; i++) + ponyint_pool_free_size(size, p[i]); + } +} + +static char pool_base_static_object[64]; + +TEST(Pool, BaseOfMemoryOutsideThePool) +{ + char on_stack[64]; + void* from_c = malloc(64); + EXPECT_EQ(nullptr, ponyint_pool_base(on_stack)); + EXPECT_EQ(nullptr, ponyint_pool_base(pool_base_static_object)); + EXPECT_EQ(nullptr, ponyint_pool_base(from_c)); + free(from_c); + +#ifndef PLATFORM_IS_ILP32 + // An address above the range the region bitmap covers isn't taken for a pool + // region. The second is far enough above that a lookup in the bitmap would + // read memory nothing maps. + EXPECT_EQ(nullptr, + ponyint_pool_base(reinterpret_cast(((uintptr_t)1 << 48) + 4096))); + EXPECT_EQ(nullptr, + ponyint_pool_base(reinterpret_cast((uintptr_t)1 << 62))); +#endif + + // An allocation too large for an arena has a mapping of its own. + size_t huge = (size_t)16 * 1024 * 1024; + char* oversized = static_cast(ponyint_pool_alloc_size(huge)); + EXPECT_EQ(nullptr, ponyint_pool_base(oversized + 64)); + ponyint_pool_free_size(huge, oversized); +} + +// An address in an arena's own header isn't in any allocation. +TEST(Pool, BaseOfAnArenaHeader) +{ + void* p = ponyint_pool_alloc_size(1024); + char* arena = reinterpret_cast( + (uintptr_t)p & ~(uintptr_t)(TEST_ARENA_SIZE - 1)); + EXPECT_EQ(nullptr, ponyint_pool_base(arena)); + EXPECT_EQ(nullptr, ponyint_pool_base(arena + 64)); + ponyint_pool_free_size(1024, p); +} + +// ponyint_pool_size_in_arena returns true for exactly the sizes whose start +// ponyint_pool_base finds, on both sides of the largest size an arena holds. +TEST(Pool, SizeInArenaMatchesBase) +{ + std::vector sizes = {32, 1024, 65536, (size_t)POOL_MAX * 2, + (size_t)16 * 1024 * 1024}; + + for(size_t k = 0; k < 4; k++) + sizes.push_back(TEST_ARENA_SIZE - (k * TEST_UNIT_SIZE)); + + bool saw_in = false; + bool saw_out = false; + + for(size_t size : sizes) + { + SCOPED_TRACE(size); + char* p = static_cast(ponyint_pool_alloc_size(size)); + bool in_arena = ponyint_pool_size_in_arena(size); + EXPECT_EQ(in_arena, ponyint_pool_base(p) != nullptr); + saw_in |= in_arena; + saw_out |= !in_arena; + ponyint_pool_free_size(size, p); + } + + EXPECT_TRUE(saw_in); + EXPECT_TRUE(saw_out); +} +#endif diff --git a/test/libponyrt/noscript/noscript.c b/test/libponyrt/noscript/noscript.c new file mode 100644 index 00000000000..b5a568b2715 --- /dev/null +++ b/test/libponyrt/noscript/noscript.c @@ -0,0 +1,25 @@ +// A program linked with the runtime but without ponyc's linker script, as a C +// program that embeds the runtime is. The bounds symbols of the descriptor and +// constant sections are then undefined, and the runtime must treat nothing as +// a descriptor or a constant. +#include +#include +#include + +int main(void) +{ + ponyint_section_bounds_init(); + + if((ponyint_desc_section_start != 0) || (ponyint_desc_section_end != 0) || + (ponyint_const_section_start != 0) || (ponyint_const_section_end != 0)) + { + printf("bounds not 0: desc %lx-%lx const %lx-%lx\n", + (unsigned long)ponyint_desc_section_start, + (unsigned long)ponyint_desc_section_end, + (unsigned long)ponyint_const_section_start, + (unsigned long)ponyint_const_section_end); + return 1; + } + + return 0; +} diff --git a/test/noalloc-link/rejected/main.pony b/test/noalloc-link/rejected/main.pony index 51aa9b7f0d1..d904d6641b2 100644 --- a/test/noalloc-link/rejected/main.pony +++ b/test/noalloc-link/rejected/main.pony @@ -18,6 +18,13 @@ class Pair fun sum(): U64 => a + b +struct Shared + embed first: Foo = Foo(1) + let m: U64 + + new create(m': U64) => + m = m' + class Holder let data: Array[U8] @@ -30,6 +37,7 @@ actor Main env.out.print(_make(n).size().string()) env.out.print(_one(n.u64()).n.string()) env.out.print(_escape(n.u64()).sum().string()) + env.out.print(_shared(n.u64()).m.string()) env.out.print(Holder(n).data.size().string()) env.out.print(_ffi().string()) env.out.print(_pure(n.u64()).string()) @@ -43,6 +51,9 @@ actor Main fun \noalloc\ _escape(x: U64): Pair => Pair(x, 2) + fun \noalloc\ _shared(x: U64): Shared => + Shared(x) + fun \noalloc\ _ffi(): I32 => _pid()