-1

After reading several blog posts and searched through SO, I know how to add a method to a class, but no one touches on how to define the method body from a String.

Here's an example blog post that gets close to what I want to do:

http://theocacao.com/document.page/327

However, the SayHello method still needs to be in the objective C code. Ideally, I would have something like:

IMP myMethod = class_addMethodFromString(@"method definition goes here...");

I also looked here: https://developer.apple.com/library/mac/documentation/Cocoa/Reference/ObjCRuntimeRef/Reference/reference.html#//apple_ref/c/func/method_setImplementation

maximus
  • 2,417
  • 5
  • 40
  • 56
  • Something might be possible, but this isn't quite clear. Can you add a snippet demonstrating what you'd like to be able to write in your code? – jscs Jun 03 '14 at 21:27
  • You have a string that contains source code, you mean? – jscs Jun 03 '14 at 21:32
  • Yes, I want to arbitrarily execute source code. – maximus Jun 03 '14 at 21:33
  • 1
    Okay, that's not possible. Or at least probably not worth the trouble. You could in fact invoke a compiler with the string as input, and then dynamically load the result. – jscs Jun 03 '14 at 21:36
  • 2
    possible duplicate of [Running arbitrary code at runtime](http://stackoverflow.com/q/9689212) and see also [Eval in ObjC](http://stackoverflow.com/q/10158036) – jscs Jun 03 '14 at 21:40
  • How would I do the approach that you mention? I know it's a long shot, I'm just wondering the dynamic loading might work. – maximus Jun 03 '14 at 21:50
  • 1
    Invoke the compiler via `system()` or `NSTask` and `dlopen()` the resulting file, I guess. I've never tried it. – jscs Jun 03 '14 at 21:52

1 Answers1

2

I don't believe this would be possible. Objective C needs to be compiled, so unless you could compile the code you're getting from that string, I don't think that could be done. The setImplementation method allows you to point at an existing, compiled chunk of code.

If you really wanted, and if the code you're running is up to you, you could execute javascript that you receive in a string format in a UIWebView (doesn't have to be added to the view, you just need an instance, I believe).

You could also intentionally cause a buffer overflow in your code, then execute arbitrary commands that way, but again, you'd be running in an already compiled environment, and would need to know the memory addresses of the code you were hoping to execute.

shortstuffsushi
  • 2,271
  • 19
  • 33