How can I debug something I cant often re-create? - swift

So I have had this bug for a long time that I have been unable to track down. The problem is I cant recreate it often.
So far I have tracked the bug down to a specific process that basically goes like this.
Their are three simultaneous processes that go on that take different lengths of time. After each process is done it sets a boolean "key" to true, and then triggers a function that checks if all "keys" are in place. Basically once the last "key" is in it will actually start to do things.
Somewhere in the key setting process, or earlier, or even possibly after it crashes. Unfortunately it leaves a really cryptic error message, and when it crashes in Xcode it is "EXEC BAD ACESS" and thus just puts a breakpoint in the app delegate declaration.
I am sure I can easily fix this bug, I just dont know enough on how to fix this. Thankfully I have fabric which allows me to print to a text file that I can see when a user crashes. Each update I add new data to it (at the cost of a tad bit of latency) in order to better understand how it happened. Each new crash gets me closer. Unfortunately though I have slow adoption rates to new versions and the crashes just keep building up! I still dont know why.
Unfortunately because this crash only happens once in a blue moon (atleast on my device) on my device. And because of the low new version updates I have to collect the data myself. Which is really hard!
I have tried tons of methods of trying to get things to go wrong, or making the process that caused it happen rapidly, or even having auto pressing buttons. Still i cant get it to crash again! And when it does all I can do to track down the bug is add more println calls so I can see what is going on.
The freaky thing is for all I know I could have already fixed it because I usually try new tweaks ect. But I won't know because it won't consistently crashes. Honestly i'm fairly sure I fixed it (or at least took down the chances of it happening).
What would you do in a situation like this?

This sound like a race condition
I would use NSOperationQueue to make sure that all he tasks are done in order and that all are actually completed before the final one is performed.

Related

How to prevent so file hacking in so file

In my app(unity5, il2cpp build), There is a function like
"GetScore()"
Unfortunately, i found the hacked version of my app in the black market. that hacked version's "GetScore()" function always returns 100. The original return value has to be under 10.
I guess this hacked App is repackaged by using like 'il2cppDumper' and changing my return value to 100;
Is there any way to prevent this problem?
Security is always a matter of making it harder for hackers - you can never make it impossible for them to tamper.
So here are some thoughts:
Obfuscation: GetScore() gets BananaJungle() - hackers cannot find the correct function without stepping through the source code for hours (hopefully)
Validate the score on multiple spots: the function calling GetScore() should do a sanity check: "is it below 10?"
In Addition to this: You may want to ignore scores above 10 to fool the hacker he succeeded. You may lock the app after 2 hours or so.
Add a ScoreLogger somewhere that logs the history of the score, so getScore() may return values <10 but someone might just overwrite the score in code to 999999. ScoreLogger will check the score history for jumps etc.
Validate Score with total playtime (approximately)
You won't ever keep hackers from hacking your games, even if it does indeed have a backing server. Just look at all the unofficial world of warcraft servers. You can keep things relatively safe if you have a server, you keep its source code secure, and your game is meaningless without its server (think Dota 2 with no multiplayer capabilities...). Even then, you can't actually validate the player's every move, unless it's a turn based game and you actually send every move the server to be processed (this works in Hearthstone, for example, but not in WoW, hence all the anti-cheating tools). EA couldn't do it, Rockstar couldn't do it, Activision couldn't do it, even the mighty Denuvo couldn't do it, you certainly can't do it.
However, you should stop and ask yourself why you want your game to be that secure. Out of every 1000 cheaters you stop, maybe one or two would actually pay. You should put in a moderate amount of effort on security (take KYL3R's advice), simply to keep honest people honest. Dishonest people will always find a way, so don't worry about them so much that you end up wasting time on (useless) security; time you could spend on making your game better.
Oh and by the way, that's also one way to keep hackers out: frequent updates to the game. They have no life, but they don't have enough time to keep making a hacked version of every game on the market every week.

IDs in Scratch: Cloud Variables

I have a multiplayer project which has some forever loops with checking code inside of them.
The problem is, multiple computers might process this and change crabx or craby due to lag in the variables dvotes, uvotes, lvotes, or rvotes. Only one machine should change this, though.
This can be easily solved by giving each player an ID like many people do in SQL. I would just check if the ID is 1, and that would be the "operating machine". I would then do all of these checks on that one machine. It would do things a Scratch server would do if you could program it...
The problem with this is that there is no way to detect when a player leaves the game. There is no block that is called "on exit" or "on stop button pressed". How would I go about doing this? I have seen people have a button which people click to exit, but some people will not click it/not even see it.
Thanks in advance!
Option 1
I've never been especially successful with cloud data myself, but I've heard the theory on this before:
Essentially, each player gets a "counter". Their computer then constantly increases that counter. If the counter ever stops increasing (which will be detected by the other computers, who are all looking after one another), the project will know that the user has left and one of the computers will take care of removing their ID and other data.
Obviously, this is much easier said than done. (As I said, I've never gotten complex cloud data to work well for myself, but I've seen it done successfully and explained.)
Option 2
Alternatively, you might be better off taking advantage of this cloud api created by MegaApuTurkUltra. I find that stealing from others tends to be the best way of solving problems when it comes to code. ;)

Track down out-of-bounds access on iPhone

I work on an average (~ 20k lines of code, Objective-C mixed with C++), and I am figthing to hunt down an EXC_BAD_ACCESS error.
I have tried all the common techniques (like enabling NSZombie, guard edges,etc.) So far, I have ruled out the possibility to access a released object, and the double-free error.
It seems that something writes on a memory space where it shouldn't. But, as many memory errors, it's not happening all the time, and it's not crashing always in the same place.
(Sometimes I receive the "object was modified after being freed" message).
Sometimes, the overwritten memory belongs to the allocator, and it crashes on malloc, or on free().
And, of course, some changes in the app may influence the bug's behaviour - if I try to comment out parts of the code, the error appears less often, so it's more difficult to find it.
Finally, I have been looking into using valgrind, but it seems that all those who used it worked on the simulator. but my code must run on the actual device (some code is ARM-specific)
Are there any general tips on how to debug such errors?
Note: The app involves video processing, so the amount of memory used is fairly large.
There are some special tools available on the XCode. You could try to use them in order to analyse your code.
http://developer.apple.com/library/mac/#featuredarticles/StaticAnalysis/index.html
It will produce some warning in case of invalid objects usage so it could help you to find a problem.
If you feel that the C++ code is causing the issue you could copy the C++ out of your iPhone project and create a Mac project. With this you could set up various stress tests. And, you should be able to use valgrind as well.

Tips for finding things in your program that are broken that you don't know about?

I was working on something for a client today when I found a way to break some functionality in our program.
(The code is really legacy code, it's been in development for about 10 years and I've only been working here for about a year.)
It didn't cause an error, or cause the program to crash, but if a user was using the program and duplicated the behavior I'm pretty sure they'd be holding up their "WTF?" flag.
In our program we have named fields (textboxes) and static text (labels) that can be linked with the textboxes. When the textbox is not filled in the label(s) that were linked to them disappear.
The functionality that I broke was, when you change the name of a textbox that already has one label or more linked to it, and save the file, without re-associating the one or more labels associated with the textbox, the formerly-associated labels appear when the textbox is blank.
Now my thinking on the matter is that a simple observer pattern could have solved this problem in the first place, but then I didn't write the code.
I was thinking that if I could dig up more situations like this with the guys in my shop, that maybe I could talk them into considering unit testing, decoupling, applying patterns where they are called for and the like.
So for this reason I was wondering if anyone had any tips for finding broken (but not error causing) functionality in any sort of app (web-based, desktop, etc...)
For an app to fail usability, it has to have a defined set of expected behaviors.
"Is this textbox SUPPOSED to do nothing when the enter key is pressed?" Maybe it is, maybe it isn't. I've seen apps where a tester/reviewer reports something that they ASSUME should work another way, when in actuality the client specifically asked that they DON'T want the form submitted on a return key press, but only a submit button click.
So basically you have to define proper behaviour before you can determine incorrect behavior.
Hire some testers.
If it has an interface, then one of my favorite unconventional test is putting 5-10 year old children in front of it. You'd be surprised what they can come up with (especially the younger ones). While this may sound like a joke, it isn't -- it really works, because children don't have the mindset of only going through "mindset" paths.
And yeah, children are the experts in "breaking things" xP.
Code inspections, i.e. reading the source code: if you had taken time to read/inspect the source code, looking for "smells" or even just looking for code whose behaviour you don't immediately understand and agree with, you might have been holding up your "WTF?" flag too.
Test, test, test.
Do unexpected things. Start doing one task and switch another to see if anything goes haywire. Use the back button when you're not supposed to. Open it in two windows. Let it time out.
Test in all browsers, especially IE.
You can find database connections/sessions aren't released by:
working out the minimum number of connections you need to do something
setting resource limits to that minimum number
ensuring one "run" of the scenario that should use exactly that number (and release it afterwards)
then run it again a few times... do you run out of connections?
I used to work in a company where programmers regularly used to forget to de-allocate db connections. The standard answer was to reduce the resource to a minimum to see if there's a leak - and to try to work out where it is by restarting the system and running different scenarios repeatedly.
The first hour of code review, with the first reviewer, will do the most to find quality problems. But here's the thing: You don't need to convince people of quality problems. You need to convince them of the value of fixing bugs, and of rewriting only when the present quality absolutely justifies it.
I've dealt with some seriously bad code in my time. But you can't just rewrite. You need a spec before you can even tell if the rewrite is an improvement.
Sometimes, you have to infer the spec from the code and then check it against some human somewhere. But by the time you've done that, you understand the code as written and are now better prepared to repair than to rewrite -- most of the time.
Repair proceeds by a process of small behavior-preserving modifications that render the spec more clear in the code. Then, when you find something that looks wrong, you don't just change it. You ask around until you find the person responsible for that decision, and you get them to show you where in the spec it says that behavior X is correct. (This conversation can take many forms.) If you're lucky, they'll tell you that behavior X is in fact incorrect, and then you've earned your pay.
assert()
Also unit testing with coverage analysis.
This is particular to the Visual Studio IDE, although it probably also applies to others:
During testing, always at some point run in the debugger with "Break when an exception is thrown" turned on.
This can often help expose exceptions which are incorrectly being silently caught and which represent bugs, but otherwise may not be evident.
Code reviews should always also include reviews of the unit test code.
The problem is that with ad-hoc testing it's impossible to know how much or how well a developer has tested their code. So, you're at the mercy of different developers definition of the word "done".
If you include reviews of the unit test code at the same time you review the production code you should have a good idea of whether the code is really complete; in that "complete" includes "tested". Not just "Hey, I'll throw it over the wall to the testers!".

How can I remove UIApplicationMain from an iPhone application?

I'm trying to port a game library over to the iPhone. Unlike SDL, this library doesn't take full control of your main() function, it's communicated with via quickly-returning functions from your own code. So, for example, obvious pseudocode:
int main() {
library_init();
// game init code here
while(we_have_not_quit_the_game) {
library_message_loop();
library_init_render();
// render stuff
library_end_render();
// update game state
}
library_shutdown();
}
iPhone makes this difficult, as it requires that you call a UIApplicationMain function that never returns. There's simply no way I could ever get back to the user code after library_init();.
I'm not convinced it's necessary - there's NSRunLoop which supposedly could be used to handle the events. I don't know if UIApplicationMain does anything else of importance, however. (Note that I have no plans to use .nib files, which is the only other thing I've found that UIApplicationMain does.)
I've got three real ideas that I can think of, but they're all a major implementation effort so I'd like to know if anyone has experience with this before I burn a day trying doomed ideas.
In Init, spawn a new thread, run UIApplicationMain in that thread. Either communicate all events across threads (ugh) or just put the UIApplicationMain thread to sleep and use a CFRunLoop in the main thread. I've heard UIApplicationMain does not like being run in a different thread, however.
Ignore UIApplicationMain entirely, just use NSRunLoop. Am I going to be missing important iPhone setup? Who knows!
Do something horrifying with longjmp() to leap out of the UIApplicationMain code after setup, pray that it doesn't do anything important during teardown.
Suggestions?
Looks like I'm answering my own question here! I'm not accepting my answer until I've been able to both test it on real hardware and get it into the app store. That said, I'll keep my Most Up-To-Date Info here, including which options didn't work.
Idea #1: It turns out that each NSRunLoop is thread-specific. If I create a UIApplicationMain in a separate thread, it doesn't get any messages. As a side effect this makes it impossible to determine when it's finished initializing, so if there's anything non-threadsafe it does, it just won't work. I may be able to send it a message across threads to figure out when it's finished initializing, but for now I'm calling this a dead end.
Idea #2: UIApplicationMain does a lot of subtle stuff. I'm not sure what it's restricted to, but I was unable to make anything work without involving UIApplicationMain. Idea #2 is right out.
Idea #3: Receiving the OS signals is important - you need to know if there's a phone-call overlay, or whether you're about to exit. On top of that, some of the setup messages seem vital in order to start the app properly. I was unable to find any method to keep messages being sent without being inside UIApplicationMain. The only options I came up with were NSRunLoop and CFRunLoop. Neither one worked - the messages didn't come in like I wanted. I may not be using these right, but in any case, Idea #3 is out.
Brand-new crazy Idea #4: It's possible to use setjmp/longjmp to fake coroutines in C/C++. The trick is to first set the stack pointer to some value that won't clobber anything important, then start your second routine, then jump back and forth, pretending like you have two stacks. Things get a tiny bit messy if your "second coroutine" decides to return from its main function, but luckily, UIApplicationMain never returns, so this isn't a problem.
I don't know if there's a way to set the stack pointer explicitly on real hardware, say, to a chunk of data that I allocated on the fly. Luckily, it doesn't matter. The iPhone has a 1MB stack by default, which is easily enough to fit a few coroutines in.
What I'm currently doing is using alloca() to push the stack pointer ahead by 768 kilobytes, then spawning UIApplicationMain, then using setjmp/longjmp to bounce back and forth between my "UI routine" and my "main routine". So far, this is working.
Caveats:
It's impossible to know when the "UI routine" has no messages to handle, and when it has no messages to handle, it will just block indefinitely until that's no longer the case. I'm solving this by making a timer that triggers every 0.1 milliseconds. Every time the timer triggers, I drop out to my "main routine", do a single game loop, then head back into the "UI routine" for another timer tick. Reading the documentation indicates that it won't stack up "timer calls" indefinitely. I do seem to get the "terminate" message appropriately, though I haven't managed to test it thoroughly yet, and I haven't tested any other important messages. (Luckily, there's only four messages total, and one of them is setup-related.)
Most modern OSes won't allocate the entire stack at once. The iPhone is probably one of these. What I don't know is whether bumping the stack pointer 3/4 of a meg forward will allocate everything "behind it", so to speak. If so, I may be effectively wasting 3/4 of a meg of RAM, which, on the iPhone, is significant. This could be handled by bumping the pointer forward a smaller amount, but this is really courting stack size disaster - it effectively limits your stack to however far you bump the pointer ahead, and you'll have to figure this out in advance. Some sentinel data in the stack, coupled with good monitoring and a logging system for stack size issues, can probably solve this, but it's a nontrivial issue. (Alternatively, if I can figure out how to muck with the stack pointer directly on the native hardware, I can just malloc()/new[] a few kilobytes, point the stack pointer at it, and use it as my new stack. I'll have to figure out how much space it needs but I doubt it'll be much, considering that it's not doing very much.)
This is currently untested on the actual hardware (give it a week or two, I got another project to finish first.)
I have no idea whether Apple will figure out what I'm doing and slap a giant REJECTED sticker on it when I try submitting to the app store. This is, shall we say, slightly outside their intentions for the API. Fingers crossed.
I'll keep this post updated, and officially accept it once I've verified that it, you know, works.
Late update: I got distracted by a variety of other things. Since then, I've had a few changes that make me far less interested in Apple development. My current approach showed no sign of not working, but I don't really have the motivation to keep fleshing it out. Sorry! If I ever change my mind I'll update this further, but Outlook Not So Good.
I know NSApplicationMain() reads Info.plist and does stuff to the app (like get the initial nib file) so I would guess that UIApplicationMain() does the same for iPhone (like get the initial status bar style, zoom the default.png image in etc.). That stuff isn't exposed anywhere else, so the functions it calls would still need to be run for the app to launch with out any side effects. You're only bet is to reverse engineer those and copy them (and hope that anything they do is in the public SDK).
Is the goal to take that main() function and have it work unmodified on the iPhone?
It would seem there's no way you're going to completely insulate the users of the library from thinking about the iPhone platform--they're going to have to deal with XCode for code signing and that sort of thing.
Given that, telling users they have to break their main() function up into a few pieces that you can call from applicationDidFinishLaunching and from an appropriate timer doesn't seem like it would inconvenience anybody much.
Why not start your game loop from within UIApplication? (Yes, you can't have it in main() but that shouldn't matter.) Some of the delegate messages are good candidates.