Skip to content

Commit ab4ae2d

Browse files
committed
Change msg_send! such that callers can properly communicate mutability
This fixes a long-standing soundness issue with how message sending is done whilst mutating the receiver, see: SSheldon/rust-objc#112. We were effectively mutating behind either `&&mut T` or `&T`, where `T` is zero-sized and contains `UnsafeCell`, so while it is still uncertain exactly how much of an issue this actually is, the approach we use now is definitely sound! Also makes it clearer that `msg_send!` does not consume `Id`s, it only needs a reference to those.
1 parent d3dc9e5 commit ab4ae2d

File tree

17 files changed

+186
-95
lines changed

17 files changed

+186
-95
lines changed

objc2-foundation/examples/custom_class.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -72,12 +72,12 @@ fn main() {
7272

7373
obj.set_number(7);
7474
println!("Number: {}", unsafe {
75-
let number: u32 = msg_send![obj, number];
75+
let number: u32 = msg_send![&obj, number];
7676
number
7777
});
7878

7979
unsafe {
80-
let _: () = msg_send![obj, setNumber: 12u32];
80+
let _: () = msg_send![&mut obj, setNumber: 12u32];
8181
}
8282
println!("Number: {}", obj.number());
8383
}

objc2-foundation/src/array.rs

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -274,13 +274,14 @@ impl<T: Message, O: Ownership> NSMutableArray<T, O> {
274274

275275
#[doc(alias = "removeLastObject")]
276276
pub fn pop(&mut self) -> Option<Id<T, O>> {
277-
self.last().map(|obj| {
278-
let obj = unsafe { Id::retain(obj as *const T as *mut T).unwrap_unchecked() };
279-
unsafe {
280-
let _: () = msg_send![self, removeLastObject];
281-
}
282-
obj
283-
})
277+
self.last()
278+
.map(|obj| unsafe { Id::retain(obj as *const T as *mut T).unwrap_unchecked() })
279+
.map(|obj| {
280+
unsafe {
281+
let _: () = msg_send![self, removeLastObject];
282+
}
283+
obj
284+
})
284285
}
285286

286287
#[doc(alias = "removeAllObjects")]

objc2-foundation/src/data.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -156,7 +156,8 @@ impl NSMutableData {
156156
impl NSMutableData {
157157
#[doc(alias = "mutableBytes")]
158158
pub fn bytes_mut(&mut self) -> &mut [u8] {
159-
let ptr: *mut c_void = unsafe { msg_send![self, mutableBytes] };
159+
let this = &mut *self; // Reborrow
160+
let ptr: *mut c_void = unsafe { msg_send![this, mutableBytes] };
160161
// The bytes pointer may be null for length zero
161162
if ptr.is_null() {
162163
&mut []

objc2-foundation/src/dictionary.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -129,7 +129,7 @@ impl<K: Message, V: Message> NSDictionary<K, V> {
129129

130130
pub fn into_values_array(dict: Id<Self, Owned>) -> Id<NSArray<V, Owned>, Shared> {
131131
unsafe {
132-
let vals = msg_send![dict, allValues];
132+
let vals = msg_send![&dict, allValues];
133133
Id::retain_autoreleased(vals).unwrap()
134134
}
135135
}

objc2-foundation/src/enumerator.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@ impl<'a, T: Message> Iterator for NSEnumerator<'a, T> {
3333
type Item = &'a T;
3434

3535
fn next(&mut self) -> Option<&'a T> {
36-
unsafe { msg_send![self.id, nextObject] }
36+
unsafe { msg_send![&mut self.id, nextObject] }
3737
}
3838
}
3939

objc2-foundation/src/value.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -177,7 +177,7 @@ mod tests {
177177
fn test_value_nsrange() {
178178
let val = NSValue::new(NSRange::from(1..2));
179179
assert!(NSRange::ENCODING.equivalent_to_str(val.encoding().unwrap()));
180-
let range: NSRange = unsafe { objc2::msg_send![val, rangeValue] };
180+
let range: NSRange = unsafe { objc2::msg_send![&val, rangeValue] };
181181
assert_eq!(range, NSRange::from(1..2));
182182
// NSValue -getValue is broken on GNUStep for some types
183183
#[cfg(not(feature = "gnustep-1-7"))]

objc2/CHANGELOG.md

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,26 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
3333
let obj: *mut Object = unsafe { msg_send![class!(NSObject), new] };
3434
let obj = unsafe { Id::new(obj) }.expect("Failed to allocate object.");
3535
```
36+
* **BREAKING**: Changed how `msg_send!` works wrt. capturing its arguments.
37+
38+
This will require changes to your code wherever you used `Id`, for example:
39+
```rust
40+
// Before
41+
let obj: Id<Object, Owned> = ...;
42+
let p: i32 = unsafe { msg_send![obj, parameter] };
43+
let _: () = unsafe { msg_send![obj, setParameter: p + 1] };
44+
// After
45+
let mut obj: Id<Object, Owned> = ...;
46+
let p: i32 = unsafe { msg_send![&obj, parameter] };
47+
let _: () = unsafe { msg_send![&mut obj, setParameter: p + 1] };
48+
```
49+
50+
Notice that we now clearly pass `obj` by reference, and therein also
51+
communicate the mutability of the object (in the first case, immutable, and
52+
in the second, mutable).
53+
54+
If you previously used `*mut Object` or `&Object` as the receiver, message
55+
sending should work exactly as before.
3656

3757
### Fixed
3858
* Properly sealed the `MessageArguments` trait (it already had a hidden

objc2/examples/introspection.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,6 @@ fn main() {
4242
}
4343

4444
// Invoke a method on the object
45-
let hash: usize = unsafe { msg_send![obj, hash] };
45+
let hash: usize = unsafe { msg_send![&obj, hash] };
4646
println!("NSObject hash: {}", hash);
4747
}

objc2/examples/talk_to_me.rs

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -31,9 +31,9 @@ fn main() {
3131
let utterance: *mut Object = unsafe { msg_send![utterance, initWithString: &*string] };
3232
let utterance: Id<Object, Owned> = unsafe { Id::new(utterance).unwrap() };
3333

34-
// let _: () = unsafe { msg_send![utterance, setVolume: 90.0f32 };
35-
// let _: () = unsafe { msg_send![utterance, setRate: 0.50f32 };
36-
// let _: () = unsafe { msg_send![utterance, setPitchMultiplier: 0.80f32 };
34+
// let _: () = unsafe { msg_send![&utterance, setVolume: 90.0f32 };
35+
// let _: () = unsafe { msg_send![&utterance, setRate: 0.50f32 };
36+
// let _: () = unsafe { msg_send![&utterance, setPitchMultiplier: 0.80f32 };
3737

38-
let _: () = unsafe { msg_send![synthesizer, speakUtterance: &*utterance] };
38+
let _: () = unsafe { msg_send![&synthesizer, speakUtterance: &*utterance] };
3939
}

objc2/src/declare.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -403,9 +403,9 @@ mod tests {
403403
#[test]
404404
fn test_custom_class() {
405405
// Registering the custom class is in test_utils
406-
let obj = test_utils::custom_object();
407-
let _: () = unsafe { msg_send![obj, setFoo: 13u32] };
408-
let result: u32 = unsafe { msg_send![obj, foo] };
406+
let mut obj = test_utils::custom_object();
407+
let _: () = unsafe { msg_send![&mut obj, setFoo: 13u32] };
408+
let result: u32 = unsafe { msg_send![&obj, foo] };
409409
assert_eq!(result, 13);
410410
}
411411

objc2/src/lib.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -42,8 +42,8 @@
4242
//! };
4343
//!
4444
//! // Usage
45-
//! let hash: NSUInteger = unsafe { msg_send![obj, hash] };
46-
//! let is_kind = unsafe { msg_send_bool![obj, isKindOfClass: cls] };
45+
//! let hash: NSUInteger = unsafe { msg_send![&obj, hash] };
46+
//! let is_kind = unsafe { msg_send_bool![&obj, isKindOfClass: cls] };
4747
//! assert!(is_kind);
4848
//! ```
4949
//!

objc2/src/macros.rs

Lines changed: 53 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -54,22 +54,32 @@ macro_rules! sel {
5454

5555
/// Sends a message to an object or class.
5656
///
57-
/// The first argument can be any type that implements [`MessageReceiver`],
58-
/// like a reference, a pointer, or an [`rc::Id`] to an object (where the
59-
/// object implements [`Message`]).
60-
///
61-
/// In general this is wildly `unsafe`, even more so than sending messages in
57+
/// This is wildly `unsafe`, even more so than sending messages in
6258
/// Objective-C, because this macro doesn't know the expected types and
6359
/// because Rust has more safety invariants to uphold. Make sure to review the
64-
/// safety section below.
60+
/// safety section below!
61+
///
62+
/// # General information
63+
///
64+
/// The syntax is similar to the message syntax in Objective-C, except we
65+
/// allow an optional comma between arguments (works better with rustfmt).
66+
///
67+
/// The first argument (know as the "receiver") can be any type that
68+
/// implements [`MessageReceiver`], like a reference or a pointer to an
69+
/// object, or even a reference to an [`rc::Id`] containing an object.
70+
///
71+
/// Each subsequent argument must implement [`Encode`].
6572
///
66-
/// The syntax is similar to the message syntax in Objective-C.
73+
/// Behind the scenes this translates into a call to [`sel!`], and afterwards
74+
/// a fully qualified call to [`MessageReceiver::send_message`] (note that
75+
/// this means that auto-dereferencing of the receiver is not supported,
76+
/// making the ergonomics when using this slightly worse).
6777
///
6878
/// Variadic arguments are not currently supported.
6979
///
7080
/// [`MessageReceiver`]: crate::MessageReceiver
71-
/// [`Message`]: crate::Message
7281
/// [`rc::Id`]: crate::rc::Id
82+
/// [`Encode`]: crate::Encode
7383
///
7484
/// # Panics
7585
///
@@ -83,13 +93,12 @@ macro_rules! sel {
8393
///
8494
/// # Safety
8595
///
86-
/// The user must ensure that the selector is a valid method and is available
87-
/// on the given receiver.
96+
/// This macro can't inspect header files to see the expected types, so it is
97+
/// your responsibility that the selector exists on the receiver, and that the
98+
/// argument types and return type are what the receiver excepts for this
99+
/// selector - similar to defining an external function in FFI.
88100
///
89-
/// Since this macro can't inspect header files to see the expected types, it
90-
/// is the users responsibility that the argument types and return type are
91-
/// what the receiver excepts for this selector. A way of doing this is by
92-
/// defining a wrapper function:
101+
/// The recommended way of doing this is by defining a wrapper function:
93102
/// ```
94103
/// # use std::os::raw::{c_int, c_char};
95104
/// # use objc2::msg_send;
@@ -99,19 +108,35 @@ macro_rules! sel {
99108
/// }
100109
/// ```
101110
///
102-
/// The user must also uphold any safety requirements (explicit and implicit)
103-
/// that the method has (e.g. methods that take pointers as an argument
104-
/// usually require that the pointer is valid and often non-null).
111+
/// This way we are clearly communicating to Rust that this method takes an
112+
/// immutable object, a C-integer, and returns a pointer to (probably) a
113+
/// C-compatible string. Afterwards, it becomes fairly trivial to make a safe
114+
/// abstraction around this.
115+
///
116+
/// In particular, you must uphold the following requirements:
117+
///
118+
/// 1. The selector is a valid method that is available on the given receiver.
119+
///
120+
/// 2. The types of the receiver and arguments must match what is expected on
121+
/// the Objective-C side.
122+
///
123+
/// 3. The call must not violate Rust's mutability rules, e.g. if passing an
124+
/// `&T`, the Objective-C method must not mutate the variable (this is true
125+
/// for receivers as well).
126+
///
127+
/// 4. If the receiver is a raw pointer the user must ensure that it is valid
128+
/// (aligned, dereferenceable, initialized and so on). Messages to `null`
129+
/// pointers are allowed (though heavily discouraged), but only if the
130+
/// return type itself is a pointer.
105131
///
106-
/// Additionally, the call must not violate Rust's mutability rules, e.g. if
107-
/// passing an `&T` the Objective-C method must not mutate the variable.
132+
/// 5. The method must not (yet, see [RFC-2945]) throw an exception.
108133
///
109-
/// If the receiver is a raw pointer the user must ensure that it is valid
110-
/// (aligned, dereferenceable, initialized and so on). Messages to `null`
111-
/// pointers are allowed (though discouraged), but only if the return type
112-
/// itself is a pointer.
134+
/// 6. You must uphold any additional safety requirements (explicit and
135+
/// implicit) that the method has (for example, methods that take pointers
136+
/// usually require that the pointer is valid, and sometimes non-null.
137+
/// Another example, some methods may only be called on the main thread).
113138
///
114-
/// Finally, the method must not (yet, see [RFC-2945]) throw an exception.
139+
/// 7. TODO: Maybe more?
115140
///
116141
/// # Examples
117142
///
@@ -132,7 +157,7 @@ macro_rules! msg_send {
132157
[super($obj:expr, $superclass:expr), $selector:ident $(,)?] => ({
133158
let sel = $crate::sel!($selector);
134159
let result;
135-
match $crate::MessageReceiver::send_super_message(&$obj, $superclass, sel, ()) {
160+
match $crate::MessageReceiver::send_super_message($obj, $superclass, sel, ()) {
136161
Err(s) => panic!("{}", s),
137162
Ok(r) => result = r,
138163
}
@@ -141,7 +166,7 @@ macro_rules! msg_send {
141166
[super($obj:expr, $superclass:expr), $($selector:ident : $argument:expr $(,)?)+] => ({
142167
let sel = $crate::sel!($($selector :)+);
143168
let result;
144-
match $crate::MessageReceiver::send_super_message(&$obj, $superclass, sel, ($($argument,)+)) {
169+
match $crate::MessageReceiver::send_super_message($obj, $superclass, sel, ($($argument,)+)) {
145170
Err(s) => panic!("{}", s),
146171
Ok(r) => result = r,
147172
}
@@ -150,7 +175,7 @@ macro_rules! msg_send {
150175
[$obj:expr, $selector:ident $(,)?] => ({
151176
let sel = $crate::sel!($selector);
152177
let result;
153-
match $crate::MessageReceiver::send_message(&$obj, sel, ()) {
178+
match $crate::MessageReceiver::send_message($obj, sel, ()) {
154179
Err(s) => panic!("{}", s),
155180
Ok(r) => result = r,
156181
}
@@ -159,7 +184,7 @@ macro_rules! msg_send {
159184
[$obj:expr, $($selector:ident : $argument:expr $(,)?)+] => ({
160185
let sel = $crate::sel!($($selector :)+);
161186
let result;
162-
match $crate::MessageReceiver::send_message(&$obj, sel, ($($argument,)+)) {
187+
match $crate::MessageReceiver::send_message($obj, sel, ($($argument,)+)) {
163188
Err(s) => panic!("{}", s),
164189
Ok(r) => result = r,
165190
}

0 commit comments

Comments
 (0)