Skip to content

[Runtime][Foundation] Supplement the class_getImageName patch with a patch to +[NSBundle bundleForClass:] on older "embedded" targets #19389

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

Merged
merged 1 commit into from
Sep 20, 2018
Merged
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
46 changes: 46 additions & 0 deletions stdlib/public/SDK/Foundation/BundleLookup.mm
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2018 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
//
//===----------------------------------------------------------------------===//

#import <Foundation/Foundation.h>

#include <objc/runtime.h>

// This method is only used on "embedded" targets. It's not necessary on
// Mac or simulators.
#if TARGET_OS_IPHONE && !TARGET_OS_SIMULATOR

/// CoreFoundation SPI for finding the enclosing bundle. This is only
/// ever called on older OSes, so there's no worry of running into
/// trouble if the implementation is changed later on.
extern "C" CFURLRef _CFBundleCopyBundleURLForExecutableURL(CFURLRef url);

@implementation NSBundle (SwiftAdditions)

/// Given an executable path as a C string, look up the corresponding
/// NSBundle instance, if any.
+ (NSBundle *)_swift_bundleWithExecutablePath: (const char *)path {
NSString *nspath = [[NSFileManager defaultManager]
stringWithFileSystemRepresentation:path length:strlen(path)];
NSURL *executableURL = [NSURL fileURLWithPath:nspath];
NSURL *bundleURL =
(NSURL *)_CFBundleCopyBundleURLForExecutableURL((CFURLRef)executableURL);
if (!bundleURL)
return nil;

NSBundle *bundle = [NSBundle bundleWithURL: bundleURL];
[bundleURL release];
return bundle;
}

@end

#endif
1 change: 1 addition & 0 deletions stdlib/public/SDK/Foundation/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ include("../../../../cmake/modules/StandaloneOverlay.cmake")
add_swift_library(swiftFoundation ${SWIFT_SDK_OVERLAY_LIBRARY_BUILD_TYPES} IS_SDK_OVERLAY
AffineTransform.swift
Boxing.swift
BundleLookup.mm
Calendar.swift
CharacterSet.swift
Codable.swift
Expand Down
2 changes: 1 addition & 1 deletion stdlib/public/runtime/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ set(swift_runtime_objc_sources
SwiftObject.mm
SwiftValue.mm
ReflectionMirror.mm
ObjCRuntimeGetImageNameFromClass.cpp
ObjCRuntimeGetImageNameFromClass.mm
"${SWIFT_SOURCE_DIR}/lib/Demangling/OldRemangler.cpp"
"${SWIFT_SOURCE_DIR}/lib/Demangling/Remangler.cpp"
"${SWIFT_SOURCE_DIR}/lib/Demangling/TypeDecoder.cpp"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,10 +25,23 @@

#include <dlfcn.h>
#include <objc/runtime.h>
#include <objc/message.h>
#include <TargetConditionals.h>

// Note: There are more #includes below under "Function patching machinery".
// Those are only relevant to the function patching machinery.

// On "embedded" targets (i.e. iOS/tvOS/watchOS devices), we need to
// patch +[NSBundle bundleForClass:] directly. The symbol table patch
// does not work for calls within the shared cache on those platforms,
// so the call within +bundleForClass: does not get patched. Instead,
// swizzle out the whole method with one that does the appropriate
// lookup for Swift classes. The symbol table patch handles this on Mac
// and simulators so this is not necessary there.
#if TARGET_OS_IPHONE && !TARGET_OS_SIMULATOR
#define PATCH_NSBUNDLE 1
#endif

using namespace swift;


Expand All @@ -40,12 +53,8 @@ typedef BOOL (*objc_hook_getImageName)(
/// \see customGetImageNameFromClass
static objc_hook_getImageName defaultGetImageNameFromClass = nullptr;

/// A custom implementation of Objective-C's class_getImageName for Swift
/// classes, which knows how to handle dynamically-initialized class metadata.
///
/// Per the documentation for objc_setHook_getImageName, any non-Swift classes
/// will still go through the normal implementation of class_getImageName,
/// which is stored in defaultGetImageNameFromClass.
/// Get the image name corresponding to a Swift class, accounting for
/// dynamically-initialized class metadata. Returns NO for ObjC classes.
static BOOL
getImageNameFromSwiftClass(Class _Nonnull objcClass,
const char * _Nullable * _Nonnull outImageName) {
Expand All @@ -63,8 +72,21 @@ getImageNameFromSwiftClass(Class _Nonnull objcClass,
*outImageName = imageInfo.dli_fname;
return imageInfo.dli_fname != nullptr;
}

return NO;
}

// If not, fall back to the default implementation.
/// A custom implementation of Objective-C's class_getImageName for Swift
/// classes, which knows how to handle dynamically-initialized class metadata.
///
/// Per the documentation for objc_setHook_getImageName, any non-Swift classes
/// will still go through the normal implementation of class_getImageName,
/// which is stored in defaultGetImageNameFromClass.
static BOOL
replacementGetImageNameFromClass(Class _Nonnull objcClass,
const char * _Nullable * _Nonnull outImageName) {
if (getImageNameFromSwiftClass(objcClass, outImageName))
return YES;
return defaultGetImageNameFromClass(objcClass, outImageName);
}

Expand Down Expand Up @@ -238,11 +260,62 @@ static const char *patchedGetImageNameFromClassForOldOSs(Class _Nullable cls) {
if (!cls)
return nullptr;
const char *result;
if (getImageNameFromSwiftClass(cls, &result))
if (replacementGetImageNameFromClass(cls, &result))
return result;
return nullptr;
}

#if PATCH_NSBUNDLE
/// Selectors for the target method, patch method, and helper method.
#define BUNDLE_FOR_CLASS_SEL @selector(bundleForClass:)
#define PATCHED_BUNDLE_FOR_CLASS_SEL @selector(_swift_bundleForClass:)
#define BUNDLE_WITH_EXECUTABLE_PATH_SEL @selector(_swift_bundleWithExecutablePath:)
Copy link
Contributor

Choose a reason for hiding this comment

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

[GitHub ate this comment the first time I submitted it; trying again.]

It seems weird to me to define a normal method for _swift_bundleWithExecutablePath: but patch _swift_bundleForClass: into place with class_addMethod. Why not either

  • always provide +_swift_bundleForClass:, and collapse +_swift_bundleWithExecutablePath: into it (but only swap them conditionally)
  • collapse +_swift_bundleWithExecutablePath: into patchedBundleForClass, since it doesn't actually use self

?

You can also avoid some of the method_exchangeImplementations dance with method_setImplementation, saving the old IMP in a static property instead of another method.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I organized it this way to keep the dependencies clean(er). The runtime side shouldn't link anything in from Foundation, but _swift_bundleForClass: wants to use the getImageNameFromSwiftClass in the runtime. I could do everything in patchedBundleForClass but it would be inconvenient to look up all of that stuff at runtime.

I used method_exchangeImplementations for thread safety. method_setImplementation would have a race condition if another thread was calling +bundleForClass: when the patch was being installed, since there's a window where the patch is active but the old IMP hasn't yet been stored into the static. Could work around that by fetching it first but then there's potential (albeit unlikely) races with other swizzlers.

Copy link
Contributor

Choose a reason for hiding this comment

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

Ooh, good catch. Okay, thanks for the explanation.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I was this close to committing a version with method_setImplementation when I had a funny thought in the back of my mind about thread safety. I've always done swizzling like that in the past, but I've always done it at startup rather than lazily like this one.


/// Whether the patch has already been done.
static bool didPatchNSBundle = false;

/// The patched version of +[NSBundle bundleForClass:]. If the class is
/// actually a Swift class and an image name can be retrieved from it,
/// look up the bundle based on that image name. Otherwise fall back to
/// the original version.
static id patchedBundleForClass(id self, SEL _cmd, Class objcClass) {
const char *imageName;
if (getImageNameFromSwiftClass(objcClass, &imageName)) {
return ((id (*)(id, SEL, const char *))objc_msgSend)(
self, BUNDLE_WITH_EXECUTABLE_PATH_SEL, imageName);
}

// Call through to the original, which is now found under the patched
// selector.
return ((id (*)(id, SEL, Class))objc_msgSend)(
self, PATCHED_BUNDLE_FOR_CLASS_SEL, objcClass);
}

/// Install the patched +[NSBundle bundleForClass:].
static void patchNSBundle(void) {
if (didPatchNSBundle) return;

Class NSBundle = objc_getClass("NSBundle");
if (!NSBundle) return;

Method origMethod = class_getClassMethod(NSBundle, BUNDLE_FOR_CLASS_SEL);
if (!origMethod) return;

// Stuff can fail below, but if it does then we can't reasonably try again.
didPatchNSBundle = true;

BOOL success = class_addMethod(
object_getClass(NSBundle), PATCHED_BUNDLE_FOR_CLASS_SEL,
reinterpret_cast<IMP>(patchedBundleForClass), method_getTypeEncoding(origMethod));
if (!success) return;

Method patchMethod = class_getClassMethod(NSBundle, PATCHED_BUNDLE_FOR_CLASS_SEL);
if (!patchMethod) return;

method_exchangeImplementations(origMethod, patchMethod);
}
#endif

/// A hook for _dyld_register_func_for_add_image that overwrites any references
/// to class_getImageName with our custom implementation.
static void patchGetImageNameInImage(const struct mach_header *mh,
Expand All @@ -251,6 +324,9 @@ static void patchGetImageNameInImage(const struct mach_header *mh,
const void *newImplementationAddr =
reinterpret_cast<const void *>(&patchedGetImageNameFromClassForOldOSs);
patchLazyPointers(mh, "_class_getImageName", newImplementationAddr);
#if PATCH_NSBUNDLE
patchNSBundle();
Copy link
Contributor

Choose a reason for hiding this comment

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

Oh, bah. I realized that since libswiftCore links against Foundation anyway it'd be okay to do this eagerly once rather than running it in the "new image loaded" callback.

Copy link
Contributor

Choose a reason for hiding this comment

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

I guess we're trying not to rely on linking to Foundation here, so okay.

#endif
}

/***************************************************************************/
Expand All @@ -267,7 +343,7 @@ void swift::setUpObjCRuntimeGetImageNameFromClass() {
auto setHook = reinterpret_cast<
void(*)(objc_hook_getImageName _Nonnull,
objc_hook_getImageName _Nullable * _Nonnull)>(setHookPtr);
setHook(getImageNameFromSwiftClass, &defaultGetImageNameFromClass);
setHook(replacementGetImageNameFromClass, &defaultGetImageNameFromClass);

} else {
// On older OSs, manually patch in our new implementation of
Expand Down