Skip to content

DNM: stdlib: Add backward deployment versions for the dynamic-replacement runtime functions - version 2 #25360

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 40 additions & 0 deletions include/swift/Runtime/DynamicReplaceable.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
//===--- DynamicReplaceable.h - dynamic replaceable support -----*- C++ -*-===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// Swift runtime support for dynamic replaceable functions.
//
//===----------------------------------------------------------------------===//

#ifndef SWIFT_RUNTIME_DYNAMIC_REPLACEABLE_H
#define SWIFT_RUNTIME_DYNAMIC_REPLACEABLE_H

#include "swift/Runtime/Config.h"

namespace swift {

/// Loads the replacement function pointer from \p ReplFnPtr and returns the
/// replacement function if it should be called.
/// Returns null if the original function (which is passed in \p CurrFn) should
/// be called.
SWIFT_RUNTIME_EXPORT
char *swift_getFunctionReplacement(char **ReplFnPtr, char *CurrFn);

/// Returns the original function of a replaced function, which is loaded from
/// \p OrigFnPtr.
/// This function is called from a replacement function to call the original
/// function.
SWIFT_RUNTIME_EXPORT
char *swift_getOrigOfReplaceable(char **OrigFnPtr);

} // end namespace swift

#endif
14 changes: 0 additions & 14 deletions include/swift/Runtime/Exclusivity.h
Original file line number Diff line number Diff line change
Expand Up @@ -40,20 +40,6 @@ SWIFT_RUNTIME_EXPORT
void swift_beginAccess(void *pointer, ValueBuffer *buffer,
ExclusivityFlags flags, void *pc);

/// Loads the replacement function pointer from \p ReplFnPtr and returns the
/// replacement function if it should be called.
/// Returns null if the original function (which is passed in \p CurrFn) should
/// be called.
SWIFT_RUNTIME_EXPORT
char *swift_getFunctionReplacement(char **ReplFnPtr, char *CurrFn);

/// Returns the original function of a replaced function, which is loaded from
/// \p OrigFnPtr.
/// This function is called from a replacement function to call the original
/// function.
SWIFT_RUNTIME_EXPORT
char *swift_getOrigOfReplaceable(char **OrigFnPtr);

/// Stop dynamically tracking an access.
SWIFT_RUNTIME_EXPORT
void swift_endAccess(ValueBuffer *buffer);
Expand Down
1 change: 1 addition & 0 deletions stdlib/public/Compatibility50/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ set(swift_runtime_linker_flags ${SWIFT_RUNTIME_CORE_LINK_FLAGS})

add_swift_target_library(swiftCompatibility50 TARGET_LIBRARY STATIC INSTALL_WITH_SHARED
ProtocolConformance.cpp
DynamicReplaceable.cpp
Overrides.cpp
C_COMPILE_FLAGS ${swift_runtime_library_compile_flags}
LINK_FLAGS ${swift_runtime_linker_flags}
Expand Down
88 changes: 88 additions & 0 deletions stdlib/public/Compatibility50/DynamicReplaceable.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
//===--- ProtocolConformance.cpp - Swift protocol conformance checking ----===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// Runtime support for dynamic replaceable functions.
//
// This implementation is intended to be backward-deployed into Swift 5.0
// runtimes.
//
//===----------------------------------------------------------------------===//

#include "Overrides.h"
#include "swift/Runtime/Exclusivity.h"
#include "swift/Runtime/Metadata.h"
#include "../runtime/ThreadLocalStorage.h"

using namespace swift;

// Mirror the SwiftTLSContext, which is defined in the runtime.
// This is a hack: the layout must match with SwiftTLSContext defined in
// Exclusivity.cpp. Fortunately it contains only a single pointer (the head of
// the access list).
class SwiftTLSContext {
void *AccessHead;

public:
void *getHead() const { return AccessHead; }

void setExtraBit() {
AccessHead = (void *)((intptr_t)AccessHead | 1);
}

void clearExtraBit() {
AccessHead = (void *)((intptr_t)AccessHead & ~1);
}

bool testExtraBit() const {
return (bool)((intptr_t)AccessHead & 1);
}
};

__attribute__((visibility("hidden"), weak))
extern "C" char *swift_getFunctionReplacement(char **ReplFnPtr, char *CurrFn) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm really wary about baking this into apps. These are pretty simple functions, which means there isn't much potential for breaking changes, but I'm paranoid that something would come up eventually.

Can we find a way to make these call the versions from libswiftCore.dylib if they exist? ARCLite accomplishes this using a terrifying technique that involves patching entries in the lazy pointer section at runtime. We could potentially do that, although it is scary.

Another option might be to use dlsym in these functions to try to find one in libswiftCore, and then call through to it if it exists. That would add a bit more overhead but it wouldn't be too horrible.

We could cut down on that overhead by having the static library include global variable function pointers that point to these functions, similar to how swift_retain etc. work. When code is compiled for older targets, have it call through the function pointers. The function pointers can point to something that decides whether to use the version from libswiftCore or the version here, then writes the appropriate function pointer back to the global variable.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes. Andy pointed out that the current implementation would bake in the ABI of how we do things.

Jordan and I talked yesterday and he proposed marking the functions in the libswiftCore.dylib weak. Something like

libswiftCore.dylib:

__attribute__(weak) // or is that __attribute__(weak_import)
void *swift_getReplacement();

The compatibility archive can then check whether the weak symbols is bound and use it if it is otherwise fall back to a compatibility version. This way you always get the current implementation and only fall back if there is not implementation. The fallback does not become ABI this way.

libcompatdynrepl.a:

void *swift_getReplacement50() {
  if (swift_getReplacement)
    return swift_getReplacement()
  ... fallback implementation
}

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good call, this is like my dlsym idea except much better.

char *ReplFn = *ReplFnPtr;
char *RawReplFn = ReplFn;

if (RawReplFn == CurrFn)
return nullptr;

void *tlsStorage = SWIFT_THREAD_GETSPECIFIC(SWIFT_RUNTIME_TLS_KEY);
if (tlsStorage) {
SwiftTLSContext *ctx = static_cast<SwiftTLSContext*>(tlsStorage);

if (ctx->testExtraBit()) {
ctx->clearExtraBit();
return nullptr;
}
}
return ReplFn;
}

__attribute__((visibility("hidden"), weak))
extern "C" char *swift_getOrigOfReplaceable(char **OrigFnPtr) {
void *tlsStorage = SWIFT_THREAD_GETSPECIFIC(SWIFT_RUNTIME_TLS_KEY);
if (!tlsStorage) {
ValueBuffer dummyAccess;
int dummyValue = 0;
swift_beginAccess(&dummyValue, &dummyAccess, ExclusivityFlags::Read, nullptr);
swift_endAccess(&dummyAccess);
tlsStorage = SWIFT_THREAD_GETSPECIFIC(SWIFT_RUNTIME_TLS_KEY);
if (!tlsStorage)
abort();
}
SwiftTLSContext *ctx = static_cast<SwiftTLSContext*>(tlsStorage);
void *pr = ctx->getHead();
ctx->setExtraBit();
char *OrigFn = *OrigFnPtr;
return OrigFn;
}

42 changes: 33 additions & 9 deletions stdlib/public/runtime/Exclusivity.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
#include "swift/Basic/Lazy.h"
#include "swift/Runtime/Config.h"
#include "swift/Runtime/Debug.h"
#include "swift/Runtime/DynamicReplaceable.h"
#include "swift/Runtime/Exclusivity.h"
#include "swift/Runtime/Metadata.h"
#include "ThreadLocalStorage.h"
Expand Down Expand Up @@ -158,13 +159,21 @@ static_assert(sizeof(Access) <= sizeof(ValueBuffer) &&

/// A set of accesses that we're tracking. Just a singly-linked list.
class AccessSet {

// Bit 0 stores an extra bit which is used by the dynamic-replaceable runtime.
// It is an "implicit" boolean parameter which is passed to a dynamically
// replaceable function.
// If true, the original function should be executed instead of the
// replacement function.
Access *Head = nullptr;

public:
constexpr AccessSet() {}

bool insert(Access *access, void *pc, void *pointer, ExclusivityFlags flags) {
auto action = getAccessAction(flags);

assert(!testExtraBit());
for (Access *cur = Head; cur != nullptr; cur = cur->getNext()) {
// Ignore accesses to different values.
if (cur->Pointer != pointer)
Expand Down Expand Up @@ -192,6 +201,7 @@ class AccessSet {
}

void remove(Access *access) {
assert(!testExtraBit());
auto cur = Head;
// Fast path: stack discipline.
if (cur == access) {
Expand All @@ -212,6 +222,18 @@ class AccessSet {
swift_runtime_unreachable("access not found in set");
}

void setExtraBit() {
Head = (Access *)((intptr_t)Head | 1);
}

void clearExtraBit() {
Head = (Access *)((intptr_t)Head & ~1);
}

bool testExtraBit() const {
return (bool)((intptr_t)Head & 1);
}

#ifndef NDEBUG
/// Only available with asserts. Intended to be used with
/// swift_dumpTrackedAccess().
Expand All @@ -227,12 +249,6 @@ class SwiftTLSContext {
public:
/// The set of tracked accesses.
AccessSet accessSet;

// The "implicit" boolean parameter which is passed to a dynamically
// replaceable function.
// If true, the original function should be executed instead of the
// replacement function.
bool CallOriginalOfReplacedFunction = false;
};

} // end anonymous namespace
Expand Down Expand Up @@ -343,17 +359,25 @@ char *swift::swift_getFunctionReplacement(char **ReplFnPtr, char *CurrFn) {
char *ReplFn = *ReplFnPtr;
if (ReplFn == CurrFn)
return nullptr;

// The "implicit" boolean parameter, which inidicates if the original function
// should be called, is passed in the extra bit of the AccessSet.
SwiftTLSContext &ctx = getTLSContext();
if (ctx.CallOriginalOfReplacedFunction) {
ctx.CallOriginalOfReplacedFunction = false;
if (ctx.accessSet.testExtraBit()) {
ctx.accessSet.clearExtraBit();
return nullptr;
}
return ReplFn;
}

char *swift::swift_getOrigOfReplaceable(char **OrigFnPtr) {
char *OrigFn = *OrigFnPtr;
getTLSContext().CallOriginalOfReplacedFunction = true;

// Use the extra bit of the AccessSet to pass the "implicit" parameter.
SwiftTLSContext &ctx = getTLSContext();
assert(!ctx.accessSet.testExtraBit());
ctx.accessSet.setExtraBit();

return OrigFn;
}

Expand Down