iOS - Add "objects" to existing app (jailbroken) - ios

How do you add "objects" to an existing app ?
For example, the EasyRefresh for Chrome tweak, enables a new button inside the iOS Chrome app, as do many other tweaks.
How may i add a simple UIButton to, for example, the Twitter app ?
Is there any GitHub projects that might help me to understand how it's done ?
Image Source: ModMyI
Thanks.

The trick involves some (very basic) reverse engineering and is made up of several steps; I'll try to explain them as clearly as possible.
Step Zero: if the app is downloaded from the AppStore, it's encrypted. You have to decrypt it using one of the scripts/applications normally used to crack apps; one command line script is poedCrack.sh (google it, you'll find it quickly on one of the paste sites), one GUI application is Crakculous (it's available in Cydia). Note that one of these are needed for easy (automatic) decryption -- the manual decryption method is way too involved to put in a StackOverflow answer, that's why I'm suggesting these tools.) However, I don't in any way encourage you to crack apps! (Basically I'm asking you not to use these tools for their original purpose :) If you want to have a look at the manual decryption process, head here.
Step One: you need to do what classes the application uses/creates. For this, you need the class-dump or class-dump-z utility. This command-line application reverses the app's binary executable file and generates interface declarations for all Objective-C classes the app uses and has inside. You can find class-dump-z, the more advanced and preferred variant here.
Step Two: after you have the class declarations, you'll have to guess which class does what and when (yep, a bit confusing). For example, in one of the files generated from above app, Google Chrome, by class-dump-z, you may find something similar:
#interface ChromeUrlToolbar: UIToolbar {
UISearchBar *urlBar;
}
- (id)initWithFrame:(CGRect)frame;
- (void)loadURL:(NSURL *)url;
#end
Well, that sounds good, doesn't it? You can see that its implementation has an initWithFrame: method (as all UIView subclasses) -- why not try to modify it?
Step Three: for this modification, you'll need MobileSubstrate. MobileSubstrate is a developer library created by Saurik, the creator of Cydia, in order to make code injection to apps easy. You can find some really good tutorials on the web, including this one.
So, you've got a class and you wanna 'hook' it -- so you write some code like this:
static IMP __original_init; // A
id __modified_init(id __self, SEL __cmd, CGRect frame) // B
{
__self = __original_init(__self, __cmd, frame); // C
// D
UIButton *newButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[newButton setTitle:#"Chrome Pwned"];
newButton.frame = CGRectMake(0, 0, 100, 40);
[__self addSubview:newButton];
return __self;
}
// E
__attribute__((constructor))
void init()
{
Class clazz = objc_getClass("ChromeUrlToolbar"); // F
MSHookMessageEx(clazz, #selector(initWithFrame:), __modified_init, &__original_init); // G
}
Explanation: let's begin from the end. The init function (E) is declared __attribute__((constructor)). That means it's automatically called when the library we'll create out of this code will be loaded into Chrome. That's exactly what we want beause we want to alter our application's behavior prior to having started it.
On the line marked // F, we capture the class object itself we want to modify. Objective-C is a highly dynamic language; that means we can get and modify information about the classes and objects at runtime. On the line marked // G, we use the most important function of the MobileSubstrate API: MSHookMessageEx. To understand how it works (rather what it does), you must know the following: Objective-C itself is implemented as a plain C library -- the language itself, under the hoods, is just simple C. So every message send in Obejctive-C is actually a C function call. These C function have two special arguments: self and cmd -- the former is the pointer to the object being messaged, the latter is the selector (a special, unique pointer to the name of the message being sent). So what MSHookMessageEx does is it takes a class and a selector, finds the implementation of the function corresponding them, and exchanges that function with the function supplied in its 3rd argument itself (__modified_init in this case). In order not to lose data, it also returns the function in its 4th parameter (here it's __original_init).
So, now the initialization of the Chrome URL toolbar is redirected to our function, what to do next? Well, nothing special: first we just call the original initialization function (notice the first two special arguments, __self and __cmd!) which creates the toolbar as if normally (this line of code is denoted by // C). Then, we do the actual alteration: in section // D, we create an UIButton, set its title and place, and add as a subview to our freshly created toolbar. Then, knowing this is an initalization function, we return back the original instance along with our button's code injected into it.
Well, that's basically what you'll need to know about this; if you're interested in deeper details of how Objective-C works and how you can create cool iOS tweaks, I suggest you to read Apple's official documentation on the topic and you can browse through some of my opensource Cydia tweaks. as well.
I hope this will help you!

You need in order to do this to understand how the Objective-C runtime works. Especially the messaging system (ie. calling a method). In particular, the methods to call are determined at runtime, vs other languages where it is at compile time.
This allows for global changing of particular methods, aka method swizzling.
Using the Mobile Substrate library you will be allowed to replace any method implementation with your own, and even call the original implementation. You need for that, of course, to know the method's name and the argument it takes, as well as the class it belongs to.
So to modify the SpringBoard for instance, you'd have to know which class in contains and which method. You'll have to use the class-dump or class-dump-z utility which does that for you (class-dump-z is more recent and more used for iOS dev, class-dump is more versatile and compatible with older binaries as well as 64 bit).
So to class-dump the SpringBoard, you'd need to enter in Terminal.app
class-dump -H /Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS5.0.sdk/System/Library/CoreServices/SpringBoard.app/SpringBoard -o ~/Desktop/SpringBoard
For class-dump-z, the -p option will generate #property instead of getters/setters, which is more clear, so you'd probably type in
class-dump-z -p -H /Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS5.0.sdk/System/Library/CoreServices/SpringBoard.app/SpringBoard -o ~/Desktop/SpringBoard
That line will create a folder on your desktop with all the classes definitions of SpringBoard.
Of course you might need to change path to one suited to your system (about that, for recent versions of Xcode, the Developer folder is in Xcode, so you'd need something like
/Applications/Xcode/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS5.1.sdk/System/Library/CoreServices/SpringBoard.app/SpringBoard
You can also find on the internet people who did that for you for most of the existing frameworks, this is pretty handy if you make sure they are at the right version for you're system.
Now, for AppStore applications, you will first need to decrypt them as they are protected. You will probably need to find the names and links of that yourselves as this is probably against the ToS of Stack Overflow, though using gdb can achieve that purpose.
To ease the work, some tools such as Logos (you will probably also need to see Theos) has been created that reduce the boilerplate code needed. There also is a (quite old) xcode template & tutorial for mobilesubstrate that provides good help.
Logos makes it easy to hook method method from class classname :
%hook classname //declares the class from your application you're going to override
-(void)method {
dosomethingnew(); //put all your new code for the method here
return %orig; //this calls the original definition of the method
}
%end //end hooking classname
For a list of the frameworks in the system and what they are usefull to, see here
Last thing : a list of popular tweaks that are opensourced (links to GitHub when possible) :
Chrome Customizer
MobileNotifier
UISettings (iOS 5 version was here also but seems to be pulled ?)
Spire
IconRenamer
Maxoimizer
IconRotator
QuickReply
WinterBoard
Veency
Some little tweaks
Finally, have a look at the WeekTweak, they release opensource tweak each week so you can learn by looking at someone else's source to try & do your own stuff. And the #theos chan on IRC (irc.saurik.com) will also provide help if you ask it kindly.

Related

Create Header and implementation file in swift

This is more of a coding style question but i believe it is valid. Coming from an obj c background i always create a .h and a .m when creating a class. However with swift that changes and all that goes into a single file. I know that for some people this is cool but i miss having these two things separate.
Quoting a comment from Zaph
"What I miss is a list of public methods as opposed to searching an
entire source file for methods not marked private. There is a
programming concept of "writing to the interface". And the public
methods should be carefully picked, not just because the developer
forgot to make some private."
is there a way to have a header - implementation class in separate files using swift? Maybe some trick?
Thanks
May be you can use Generated Interface to view all the public methods and properties. You can find that option at the bottom of related files popup in the upper-left of the source editor window. To switch back, click Original Source in the same pop up.
Shortcut: control + cmd + down arrow
This is how generated interface file looks.
As far as i'm aware, this cannot be done. That being said, if set out your .swift files correctly then they are still very readable. I tend to follow this as a guideline for styling in swift and i find that it breaks things up into readable sections, especially by using // MARK: as well.
In short, no.. But what do you miss..? Once you get used to it, you will probably prefer it like this! The old separation has no clear advantage over this new one!
More and more languages use this approach, as it reduce coupling and errors.
So when you change the signature of a function, to need to check another file to update it, it's only duplication without any added value.
The problem you describe (how to see only "public" functions) is usually done buy tools( IDE) or documentation generators.
You can create 2 swift files:
YourClassNameHeader.swift
class YourClassName {// put here all your properties
}
YourClassNameMethods.swift or YourClassNamePrivate.swift
extension YourClassName { // put here all private methods and
properties }
But in general its not good practise

How to load new generated private API headers in iOS?

I'm dummy in iOS especially in private API.
I have application for testing and now I need to use private API (this application not for App Store).
I downloaded generated headers from iOS-Runtime-Headers and what next?
Under /System/Library/ I have list of libraries that contain Frameworks, ... ,PrivateFrameworks as well.
Do I need to replace original framework with ones I copied from iOS-Runtime-Headers?
Because I have other applications that use Public API only and I don't want to damage them.
From posted link they tell to validate library for example by:
NSBundle *b = [NSBundle
bundleWithPath:#"/System/Library/PrivateFrameworks/GAIA.framework"];
BOOL success = [b load];
But here the path points to original path.
Or I miss something,
Thank you
First of all, don't replace any headers which are provided by Apple.
Generally, it's done one of two ways:
1) You can copy some of these headers to your project and just include these files the same way as you include any other headers
#import "SomeHeader.h"
2) Sometimes you have to sanitize them (edit them) a little bit. Quite often, these headers has something like in in them:
#import "NSObject.h"
And compliller won't be able to find it, because NSObject is built-in class. So, you need to remove this like.
3) If you just need couple of methods out of it, then Tuukka Nori solution is right.
On top of these, you will need to link (statically or dynamically) against appropriate private framework (just including headers isn't enough).
Don't replace any files. Instead, write a header file with the symbol that you intend to use. If you need an Objective-C method, add a category with a unique name, e.g.
#interface NSString (MyOwnPrivateCategory)
- (void) privateMethodDeclaredInRuntimeHeaders;
#end
Import it and use the method as you like.
The sample code given shows how to load a framework at runtime in case you don't want to link to it. Since some frameworks are private, they might not be available in all versions of iOS.

Using hidden properties vs. private iVars

This question is specifically focused around static libraries / frameworks; in other words, code that other people will eventually touch.
I'm fairly well versed in properties, since I started iOS development when iOS 6 was released. I have used hidden properties declared in interface extensions to do all of my "private" property work, including using readonly on public facing properties I don't want others to modify and readwrite within interface extensions.
The important thing is that I do not want other people who are using these static libraries / frameworks to be accessing these properties if I don't allow it, nor writing these properties if I let them read it.
I've known for a while that they could theoretically create their own interface extension and make my readonly properties readwrite themselves, or guess the names of hidden properties.
If I want to prevent this, should I be using ivars with the #private tag with directly declared ivars? Are there potential downfalls to doing it this way? Does it actually get me an additional measure of security, or is it a red herring?
Under ARC the only mode supported by properties and not instance variables is copy - so if you need copy use a property.
If you declare your private instance variables in the #implementation section:
#implementation MyClass
{
// private instance vars
}
then it takes serious effort to access them from outside the class. As you say accessing a "private" property just takes guessing its name - or using the library calls which tell you.
Is it worth it for security? YMMV. But its a good coding practice regardless.
Addendum
As the comment trail shows there has been much discussion over my use of serious effort.
First let's be clear: Objective-C is in the C family of languages, they all allow the programmer to just about anything they choose while staying within the language[*] - these are not the languages of choice if you want strong typing, access restrictions, etc., etc. within your code.
Second, "effort" is not an absolute measure! So maybe I should have chosen the word "obvious" to qualify it rather than "serious". To access a private property just requires the use of a standard method call where the object has type id - there is little clue in the code that the method being called is hidden. To access a private variable requires either an API call (a runtime function or KVC call) or some pointer manipulation - the resultant code looks nothing like a standard variable assignment. So its more obvious.
That said, apart from uses requiring copy, under ARC there is no good reason to use a private property when a private instance variable will do. For a private variable fred compare:
self.fred = 42; // property access, may involve a call (if not optimised out)
_fred = 42; // common way to bypass the accessors and get at the underlying var
fred = 42; // direct access
Take your pick, there is no right answer, but there isn't a wrong one either - this is the realm of opinion (and that is of course an opinion ;-)). I would often pick the last one, private variable - clean & simple. However #RobNapier in his answer prefers the use of properties.
[*] Note: once you consider linking to external code, say written in assembler, all bets are of in any language. At that point you have to look at the "hardware" (real or virtual) and/or "OS" to provide protection.
You should use private ("hidden") properties here. There is no "security" risk. The "attacker" in this scenario is the caller. The caller has complete access to all memory in the process. She can access anything in your framework she wants and there is absolutely nothing you can do to stop that (nor should you). This is true in any language. You can bypass "private:" designations in C++ as well if you know what you're doing. It's all just memory at the end of the day.
It is not your job to protect yourself or your framework from the caller. You both have the same goal: correct program behavior. Your goal is to protect callers from themselves. Make it difficult for them to use your framework incorrectly and easy to use it correctly.
So, you should use the tool that leads to the most correct code. And that tool is properties, and avoiding directly ivar access except in init and dealloc.

What percent of functions on OS X are called by the Objective-C runtime?

I'd like to get a firmer grasp of how frequently the runtime in any language that requires one is being called. In this case, I'm specifically interested in knowing:
Of all the function calls getting executed on an OS X or iOS system in any given second (approximations are of course necessary) how many of those are Objective-C runtime functions (i.e. functions that are defined by the runtime)?
Of course it depends on your application, but in general the answer is "a whole lot". Like, a whole freaking lot.
If you really want to see numbers, I'd recommend using dtrace to log all runtime functions as they're called. This blog entry talks about how to do such a thing.
A lot. Here are just a few examples.
Every time you send a message, the actual message sending is done by a runtime function (this is in fact the most called runtime function in pretty much any objective C program).
NSObject class and protocol are not part of the standard library but part of the runtime, therefore any method that ends up executing to the default NSObject implementation is in fact executing runtime code.
Every time you execute a default property accessor (either read or write), that's part of the runtime.
If you use ARC, every time you access a weak reference (either for reading or writing it) that's a runtime function.
Objc runtime includes the C runtime, so anything that involves a C runtime function (for example passing a large structure by value or returning it) is in fact calling into the runtime.
and more.

How do programmers practice code reuse

I've been a bad programmer because I am doing a copy and paste. An example is that everytime i connect to a database and retrieve a recordset, I will copy the previous code and edit, copy the code that sets the datagridview and edit. I am aware of the phrase code reuse, but I have not actually used it. How can i utilize code reuse so that I don't have to copy and paste the database code and the datagridview code.,
The essence of code reuse is to take a common operation and parameterize it so it can accept a variety of inputs.
Take humble printf, for example. Imagine if you did not have printf, and only had write, or something similar:
//convert theInt to a string and write it out.
char c[24];
itoa(theInt, c, 10);
puts(c);
Now this sucks to have to write every time, and is actually kind of buggy. So some smart programmer decided he was tired of this and wrote a better function, that in one fell swoop print stuff to stdout.
printf("%d", theInt);
You don't need to get as fancy as printf with it's variadic arguments and format string. Even just a simple routine such as:
void print_int(int theInt)
{
char c[24];
itoa(theInt, c, 10);
puts(c);
}
would do the trick nickely. This way, if you want to change print_int to always print to stderr you could update it to be:
void print_int(int theInt)
{
fprintf(stderr, "%d", theInt);
}
and all your integers would now magically be printed to standard error.
You could even then bundle that function and others you write up into a library, which is just a collection of code you can load in to your program.
Following the practice of code reuse is why you even have a database to connect to: someone created some code to store records on disk, reworked it until it was usable by others, and decided to call it a database.
Libraries do not magically appear. They are created by programmers to make their lives easier and to allow them to work faster.
Put the code into a routine and call the routine whenever you want that code to be executed.
Check out Martin Fowler's book on refactoring, or some of the numerous refactoring related internet resources (also on stackoverflow), to find out how you could improve code that has smells of duplication.
At first, create a library with reusable functions. They can be linked with different applications. It saves a lot of time and encourages reuse.
Also be sure the library is unit tested and documented. So it is very easy to find the right class/function/variable/constant.
Good rule of thumb is if you use same piece three times, and it's obviously possible to generalize it, than make it a procedure/function/library.
However, as I am getting older, and also more experienced as a professional developer, I am more inclined to see code reuse as not always the best idea, for two reasons:
It's difficult to anticipate future needs, so it's very hard to define APIs so you would really use them next time. It can cost you twice as much time - once you make it more general just so that second time you are going to rewrite it anyway. It seems to me that especially Java projects of late are prone to this, they seem to be always rewritten in the framework du jour, just to be more "easier to integrate" or whatever in the future.
In a larger organization (I am a member of one), if you have to rely on some external team (either in-house or 3rd party), you can have a problem. Your future then depends on their funding and their resources. So it can be a big burden to use foreign code or library. In a similar fashion, if you share a piece of code to some other team, they can then expect that you will maintain it.
Note however, these are more like business reasons, so in open source, it's almost invariably a good thing to be reusable.
to get code reuse you need to become a master of...
Giving things names that capture their essence. This is really really important
Making sure that it only does one thing. This is really comes back to the first point, if you can't name it by its essence, then often its doing too much.
Locating the thing somewhere logical. Again this comes back to being able to name things well and capturing its essence...
Grouping it with things that build on a central concept. Same as above, but said differntly :-)
The first thing to note is that by using copy-and-paste, you are reusing code - albeit not in the most efficient way.
You have recognised a situation where you have come up with a solution previously.
There are two main scopes that you need to be aware of when thinking about code reuse. Firstly, code reuse within a project and, secondly, code reuse between projects.
The fact that you have a piece of code that you can copy and paste within a project should be a cue that the piece of code that you're looking at is useful elsewhere. That is the time to make it into a function, and make it available within the project.
Ideally you should replace all occurrances of that code with your new function, so that it (a) reduces redundant code and (b) ensures that any bugs in that chunk of code only need to be fixed in one function instead of many.
The second scope, code reuse across projects, requires some more organisation to get the maximum benefit. This issue has been addressed in a couple of other SO questions eg. here and here.
A good start is to organise code that is likely to be reused across projects into source files that are as self-contained as possible. Minimise the amount of supporting, project specific, code that is required as this will make it easier to reuse entire files in a new project. This means minimising the use of project specific data-types, minimising the use project specific global variables, etc.
This may mean creating utility files that contain functions that you know are going to be useful in your environment. eg. Common database functions if you often develop projects that depend on databases.
I think the best way to answer your problem is that create a separate assembly for your important functions.. in this way you can create extension methods or modify the helper assemble itself.. think of this function..
ExportToExcel(List date, string filename)
this method can be use for your future excel export functions so why don't store it in your own helper assembly.. i this way you just add reference to these assemblies.
Depending on the size of the project can change the answer.
For a smaller project I would recommend setting up a DatabaseHelper class that does all your DB access. It would just be a wrapper around opening/closing connections and execution of the DB code. Then at a higher level you can just write the DBCommands that will be executed.
A similar technique could be used for a larger project, but would need some additional work, interfaces need to be added, DI, as well as abstracting out what you need to know about the database.
You might also try looking into ORM, DAAB, or over to the Patterns and Practices Group
As far as how to prevent the ole C&P? - Well as you write your code, you need to periodically review it, if you have similar blocks of code, that only vary by a parameter or two, that is always a good candidate for refactoring into its own method.
Now for my pseudo code example:
Function GetCustomer(ID) as Customer
Dim CMD as New DBCmd("SQL or Stored Proc")
CMD.Paramaters.Add("CustID",DBType,Length).Value = ID
Dim DHelper as New DatabaseHelper
DR = DHelper.GetReader(CMD)
Dim RtnCust as New Customer(Dx)
Return RtnCust
End Function
Class DataHelper
Public Function GetDataTable(cmd) as DataTable
Write the DB access code stuff here.
GetConnectionString
OpenConnection
Do DB Operation
Close Connection
End Function
Public Function GetDataReader(cmd) as DataReader
Public Function GetDataSet(cmd) as DataSet
... And So on ...
End Class
For the example you give, the appropriate solution is to write a function that takes as parameters whatever it is that you edit whenever you paste the block, then call that function with the appropriate data as parameters.
Try and get into the habit of using other people's functions and libraries.
You'll usually find that your particular problem has a well-tested, elegant solution.
Even if the solutions you find aren't a perfect fit, you'll probably gain a lot of insight into the problem by seeing how other people have tackled it.
I'll do this at two levels. First within a class or namespace, put that code piece that is reused in that scope in a separate method and make sure it is being called.
Second is something similar to the case that you are describing. That is a good candidate to be put in a library or a helper/utility class that can be reused more broadly.
It is important to evaluate everything that you are doing with an perspective whether it can be made available to others for reuse. This should be a fundamental approach to programming that most of us dont realize.
Note that anything that is to be reused needs to be documented in more detail. Its naming convention be distinct, all the parameters, return results and any constraints/limitations/pre-requisites that are needed should be clearly documented (in code or help files).
It depends somewhat on what programming language you're using. In most languages you can
Write a function, parameterize it to allow variations
Write a function object, with members to hold the varying data
Develop a hierarchy of (function object?) classes that implement even more complicated variations
In C++ you could also develop templates to generate the various functions or classes at compile time
Easy: whenever you catch yourself copy-pasting code, take it out immediately (i.e., don't do it after you've already CP'd code several times) into a new function.

Resources