Is it safe to replace a StringStorage by a NSString with low level memory write?

I am learning some swift runtime hackery, I want to tamper with a class instance variable of type String. The Swift 5 class is defined as below:

class MyClass {
var foo: String
var bar: String
}

on iOS for ARM64 each instance variable is layed out sequentially in memory, but they occupy 2 words (16 bytes). I don't know the purpose of the first word, it seems to be a tagged pointer which includes the length of the string. The next pointer is a reference to StringStorage, internally that class is named "Swift.__StringStorage". Is it safe to replace this pointer by an instance of NSString?

You would need to also edit the flags in the first word to tell String that it has a different type of backing store now. And, just in general, this is not a safe or supported thing to do.

It's expected to rely on implementation specific, not stable behaviors when hacking things. It's not a concern to me.

What flags should I set instead? Actually it's 0xF0 for the StringStorage.

Thanks!

Just out of curiosity, even for exploration purposes, why are you doing this rather than using bridging to create a new String?

I am using frida to explore it at runtime, I use its JavaScript wrappers over ObjectiveC classes.

Can I do that bridging without access to the original application source code, not even debug symbols?

1 Like