Skip to content
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

Soundness issue with dynamic downcasts #75824

Open
dabrahams opened this issue Aug 10, 2024 · 0 comments
Open

Soundness issue with dynamic downcasts #75824

dabrahams opened this issue Aug 10, 2024 · 0 comments
Labels
bug A deviation from expected or documented behavior. Also: expected but undesirable behavior. triage needed This issue needs more specific labels

Comments

@dabrahams
Copy link
Contributor

dabrahams commented Aug 10, 2024

Description

Two modules can make the same type conform to a protocol P with different associated types. If a generic type constrained on P contains the associated type, it will have a different layout in each of the two modules. Something about name mangling appears to be preventing these different layouts from coexisting in most contexts (causing link errors, which isn't a great user experience, but it works). However dynamic downcasting circumvents that protection and will allow me to, e.g. put an element of size 8 into an array of elements with size 1. It's possible that mangling conformance information into the type ID information used for downcasting could fix this particular case, but the general case of downcasting to existential types may be harder.

Reproduction

https://github.com/dabrahams/swift-unsound demonstrates (run the tests).

On my machine, the final print statement outputs a bunch of null characters that shouldn't be there, and if you make this change the test actually crashes for me with a segfault. All the code is entirely safe:

diff --git a/Sources/M1/M1.swift b/Sources/M1/M1.swift
index 9818b1d..3cbe219 100644
--- a/Sources/M1/M1.swift
+++ b/Sources/M1/M1.swift
@@ -1,9 +1,9 @@
 import M0
 extension Int: P {
-  public typealias X = Bool
+  public typealias X = String
 }
 
 public func makeA() -> Any {
   print("returning A<Int> with size", MemoryLayout<A<Int>>.size)
-  return A<Int>(false)
+  return A<Int>("Hello")
 }

Expected behavior

build failure

Environment

swift-driver version: 1.90.11.1 Apple Swift version 5.10 (swiftlang-5.10.0.13 clang-1500.3.9.4)
Target: x86_64-apple-macosx14.0

Additional information

No response

@dabrahams dabrahams added bug A deviation from expected or documented behavior. Also: expected but undesirable behavior. triage needed This issue needs more specific labels labels Aug 10, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug A deviation from expected or documented behavior. Also: expected but undesirable behavior. triage needed This issue needs more specific labels
Projects
None yet
Development

No branches or pull requests

1 participant