Advanced+apple+debugging (13)

Source: Internet
Author: User
<span id="Label3"></p>This article focuses on what you can do with the knowledge of the Lldb Python module and the Objective-c Runtime. When Lldb parses a streamlined executable file (an executable file that does not have dwarf debug information), lldb does not have symbolic information for the stack Record.<br>instead, LLDB will generate a synthesized name for a method it knows as a method name, but I don't know what to call this Method.<br>Here is an example of a synthetic method name created by lldb:<p><p></p></p><p><p>___lldb_unnamed_symbol906$ $SpringBoard<br>A reverse engineering the strategy for the name of this method is to create a breakpoint in this method and then browse the register when the method starts Executing.<br>With your objective-c run-time assembly knowledge, You know that the RSI register (X64) or X1 register (ARM64) will store the name Objective-c Selector. In addition, you have rdi (x64) or X0 (ARM64) registers holding references to this instance (or class).<br>however, as soon as you leave the function name of the function implementation location, you cannot guarantee that the value in the register is the value we want, because their values are likely to be Rewritten. What happens if a streamlined function calls another function? Then the values in the registers you care about will be lost, because I they are set to the parameters of this new Function. You need a way to re-symbolize the stack record without having to come up with these Registers.<br>In this chapter, you will build a LLDB script that can re-symbolize the streamlined objective-c function in the stack Record.</p></p><p><p>Picture. png</p></p><p><p>When you call BT on this process, LLDB does not have the function name of the highlighted Part.<br>You will build a new call to SBT that can look at the streamlined functions and try to use these functions to re-symbolize commands using the Objective-c Runtime. At the end of this chapter, your SBT command will produce the following results:<br>Picture. png<br>The objective-c functions that have been streamlined have now been re-symbolized. Because these scripts are independent, you can run this new SBT script on any objective-c executable file that lldb can attach to.</p></p><p><p>How do you do this exactly?</p></p><p><p>Let's start by discussing how to re-symbolize the Objective-c code with the Objective-c Runtime.<br>If you have the full path to this module, the runtime of objective-c can list all the class names in a particular module (a dynamic library that is mapped to the main execution file, a nsbundle, and so on). This can be achieved through the OBJC_COPYCLASSNAMESFORIMAGEAPI.<br>Starting here, You can use the Class_copymethodlist API to list the class methods and instance methods in all classes returned by the Objc_copyclassnamesforimage Method.<br>therefore, You can crawl all the method addresses and compare those addresses to the addresses in the stack Record. if the function of the stack record cannot generate a default function name (for example, If Sbsymbol is a lldb composite), then you can assume that LLDB has no debug information at this ADDRESS.<br>Using Lldb's python module, You can get the starting address of a function-even if a function has already executed a portion of the ADDRESS. This is to use Sbvalue to refer to a sbaddress. From here, you can compare the starting address of all the objective-c methods that you have obtained for the Sbsymbol Synthesis. If there are two addresses that match, then you can replace the condensed (synthetic) method name and replace it with the function name contained in the Objective-c Runtime.<br>Don't worry: before we build these Python scripts, you'll be using the lldb Script command system to learn these things.</p></p><p><p>Shades of Ray</p></p><p><p>Include an application called "ray shades" in the starter Folder. I have a very good name for the project that shows many of Ray Wenderlich's Faces.<br>This is the gentleman ray, This is the superhero ray, That's the ray! of the Puzzle.<br>Picture. png</p></p><p><p>When you click the bottom button, a randomly generated random-sized Ray's picture will pop up.<br>wow, it will generate revenue on the app store!<br>Open the Shades of Ray project and then frame and run the app. In the Xcode project, there are two Scheme. Make sure you select the shades of Ray scheme instead of the stripped Scheme. YOU'LL use that streamlined scheme in the BACK.<br>If you have randomly generated a picture of ray, click Objcuibarbuttonitem in the Upper-right corner.<br>Picture. png</p></p><p><p>This uibarbuttonitem binds a ibaction that prints out all the methods implemented in the main execution file and outputs them to your console.<br>In fact, you can see the names of the methods that are exported to the console!<br>Locate The-[viewcontroller dumpobjcmethodstapped:] method in the Console. this is how you extract all the objective-c methods in the main execution file.<br>In front of this function is a number (in my case the number is, 4483016672), this number holds the starting address of this objective-c method.<br>Don't you believe me? pause execution and enter the following in Lldb:<br>(lldb) Image Lookup-a 4483016672<br>Your address may be somewhat different from mine. This command extracts 4483016672 of the address in memory and views its related references in your project.</p></p><p><p>Address:50 shades of ray[0x00000001000017e0] (shades of<br>Ray. <strong>TEXT.</strong> Text + 624)<br>Summary:50 shades of Ray '-[viewcontroller dumpobjcmethodstapped:] at<br>Viewcontroller.m:36<br>Very ingenious. This tells us where 4483016672 is in memory, where-[viewcontroller dumpobjcmethodstapped:] is loaded into memory. Let's look at the code for this Method.<br>Go to the top of VIEWCONTROLLER.M and find Dumpobjcmethodstapped:. Its comments are written in detail and do not need to be overly described here, but there are a few points to note:<br>? All methods implemented in the master execution file are enumerated by Objc_copyclassnamesforimage.<br>? For each class, there is a logic that captures all of the class methods and instance METHODS.<br>? In order to fetch a class method of a particular objective-c class, you must get the meta class. The Meta class is a static method that is responsible for responding to a class. For example, all methods starting with + are implemented by meta instead of the class Itself.<br>? All methods are gathered in a nsmutabledictionary, and the key in the dictionary is the location of each method in Memory.</p></p><p><p>Use scripts to guide your path</p></p><p><p>It's time to use the script-generated lldb command to navigate through the APIs of the Lldb module and build a quick POC to see how you start an address in memory for a Function.<br>In the Lldb console, set a breakpoint at Nslog:</p></p><p><p>(lldb) b NSLog<br>You will trigger sbbreakpointlocation multiple Times. That's a good Thing. Now continue running the Application.<br>In the emulator, click the OBJC button in the Upper-right corner.<br>Execution should stop properly before the content is output to Stderr.<br>Using the global variable lldb.frame, you can dig out which APIs allow you to grab the starting address of the NSLog Function.<br>Start building and use global variables Here:</p></p><p><p>(lldb) Script Print Lldb.frame<br>You will get <strong>str</strong>() representing Sbframe. There is no fresh stuff.</p></p><p><p>Frame #0:0x000000010b472390 Foundation ' NSLog<br>If you decide to use Gdocumentation to search for sbframe documents (from 19th chapter, "Script bridging Classes and Hierarchy"), you will see sbframe have some potential ways to get the starting address of a Function. The PC looks like a rip register (X64) or a PC (ARM64), but they only take effect at the beginning of the Function. You need to fetch the starting address from any offset in the Sbframe.<br>unfortunately, There is no APIs in Sbframe that you can use to get the starting address from any of the Function's instruction Offsets. You need to shift your attention to other classes referenced by Sbframe to find what you need.<br>Fetch Sbsymbol references from sbframe:</p></p><p><p>(lldb) Script Print Lldb.frame.symbol<br>Sbsymbol is responsible for the offset address of the Nslog. In other words, Sbsymbol will tell you where the function is implemented in the module; It is not the actual address that the NSLog function is loaded into memory.<br>however, You can use the Sbaddress property along the Getloadaddressapi of the Sbaddress property to discover where NSLog is starting in your current process.</p></p><p><p>(lldb) Script Print lldb.frame.symbol.addr.GetLoadAddress (lldb.target)<br>You will get a 10-digit number. what I get is 4484178832. use LLDB to convert it to 16 and then compare the starting address of the output nslog:</p></p><p><p>(lldb) p/x 4484178832<br>The 16 binary address I get is 0x000000010b472390.<br>Compare your output to the real address of the NSLog function to see if they match.</p></p><p><p>Picture. png</p></p><p><p>Wow! It's a match! This is the process of re-symbolizing Us.</p></p><p><p>Lldb.value with Nsdictionary</p></p><p><p>Since you've already read this, You can view more Content. How do you parse the nsdictionary where all the addresses are gathered?<br>You will copy the code and almost verbatim copy all of the generated methods and apply them to Evaluateexpressionapi to get Sbvalue.<br>You should still pause in the start position of the Nslog. Jumps to the frame that Calls-[viewcontroller dumpobjcmethodstapped:].</p></p><p><p>(lldb) F 1<br>This will get the previous frame, Dumpobjcmethodstapped:. Now that you have accessed all the variables in this method, the retdict contains all the methods that are responsible for extracting the implementation in the main executable file.<br>Fetch a reference to the Sbvalue description Retdict.</p></p><p><p>(lldb) script Print lldb.frame.FindVariable (' retdict ')<br>This line of instructions will print out the retdict sbvalue:</p></p><p><p>(__nsdictionarym *) retdict = 0x000060800024ce10 Key/value pairs<br>Since this is a nsdictionary, you actually need to dereference this value so that you can enumerate his content.</p></p><p><p>(lldb) script Print lldb.frame.FindVariable (' retdict '). deref<br>You will get more relevant output (just part of the output below):</p></p><p><p>(__nsdictionarym) *retdict = {<br>[0] = {<br>Key = 0x000060800002bb80 @ "4411948768"<br>Value = 0x000060800024c660 @ "-[appdelegate window]"<br>}<br>[1] = {<br>Key = 0x000060800002c1e0 @ "4411948592"<br>Value = 0X000060800024DD10 @ "-[viewcontroller toolBar]"<br>}<br>[2] = {<br>Key = 0X000060800002BC00 @ "4411948800"<br>Value = 0x000060800024c7e0 @ "-[appdelegate setWindow:]"<br>}<br>[3] = {<br>Key = 0x000060800002bba0 @ "4411948864"<br>Value = 0x000060800004afe0 @ "-[appdelegate. cxx_destruct]"<br>}<br>This is where you start, because it prints out the values of all keys.<br>Create a lldb.value outside of this sbvalue and assign it to A.</p></p><p><p>(lldb) Script a = lldb.value (lldb.frame.FindVariable (' retdict '). Deref)<br>This is a performance I prefer to use lldb.value rather than Sbvalue. here, you can easily browse the values in the Nsdictionary.<br>Print out the first value in the Lldb.value nsdictionary.</p></p><p><p>(lldb) Script Print a[0]<br>here, You can print out key or value at the same time.<br>First print out key:</p></p><p><p>(lldb) Script Print A[0].key<br>You will get some output similar to the Following:</p></p><p><p>(__nscfstring *) key = 0x000060800002bb80 @ "4411948768"<br>Then print out value:</p></p><p><p>(lldb) Script Print A[0].value<br>This will print something similar to the following:</p></p><p><p>(__nscfstring *) value = 0x000060800024c660 @ "-[appdelegate window]"<br>Picture. png</p></p><p><p>If you only want the return value without the reference address, you need to indicate that the lldb.value is returned to a sbvalue and then crawl the Description.<br>(lldb) Script Print A[0].value.sbvalue.description<br>This will output your desired-[appdelegate window]. Note that you may have a different Approach.<br>If you want to extract all keys from this lldb.value instance, you can use the Python array to try to extract all the Key.</p></p><p><p>(lldb) script print ' \ n '. join ([x.key.sbvalue.description for X in A])<br>You will get some output similar to the Following:</p></p><p><p>4411948768<br>4411948592<br>4411948800<br>4411948864<br>4411948656<br>4411948720<br>4411949072<br>4411946944<br>4411946352<br>4411946976<br>Extract all of the value in the same way:</p></p><p><p>(lldb) script print ' \ n '. join ([x.value.sbvalue.description for X in A])<br>Now that you know how to dissect this nsdictionary, imagine if it was replaced by some JIT code ...<br>Our plan is to copy the code from dumpobjcmethodstapped: to a Python script and execute it as a JIT code. here, you need to use the same program to parse it out of the Nsdictionary.<br>Sounds pretty good, doesn't it? now that your plan is ready, go to the next section!</p></p><p><p>Streamlined shades of Ray</p></p><p><p>yes, This headline attracts your attention, doesn't it?<br>In the shades of Ray's Xcode schemes, There is a scheme called stripped shades of ray.<br>Stop executing the current process (? +.) Then choose stripped 50Shades of Ray this Scheme.</p></p><p><p>Picture. png</p></p><p><p>This scheme will build a debugger executable, but remove debugging information that you are accustomed to in your day-to-day development. build and Run. This project contains a shared Symbolicbreakpoint. Enable this Breakpoint.<br>There is no need to modify this symbol breakpoint, but this breakpoint does when the value of Han Wu.</p></p><p><p>This breakpoint will stop At-[uiview initwithframe:] and there is a condition that only stops when the UIView class is the type of RAYVIEW. The Rayview teacher shows the portrait of the cute ray Wenderlich.<br>Click <strong>Generate a ray!</strong> Button. Execution will stop at The-[uiview initwithframe:] method.<br>Note the observation stack Record.</p></p><p><p>Picture. png</p></p><p><p>There are some interesting things at the first and third frames: there is no debug information. Lldb default generates a synthesized function name for these METHODS.<br>Confirm this point in the Lldb.<br>In lldb, make sure you re-start the frame position (initwithframe:):</p></p><p><p>(lldb) F 0<br>Use a script to see if some of it is synthetic:</p></p><p><p>(lldb) Script Lldb.frame.symbol.synthetic<br>You're going to get False. It's understandable, because you know it's Initwithframe:. Jump to the top of a composite frame:</p></p><p><p>(lldb) F 1<br>To execute the logic of the previous script:</p></p><p><p>(lldb) Script Lldb.frame.symbol.synthetic<br>This time you get the result will be True.</p></p><p><p>Build sbt.py</p></p><p><p>Include this Python script named sbt.py in the starter Folder.<br>Paste this script into your ~/lldb directory. Assuming you have installed the lldbinit.py script, This will load all the Python files in the lldb directory.<br>If you do not see Chapter 22nd, "SB Examples, Improved Lookup", You can manually install sbt.py by modifying your ~/.lldbinit File.<br>If you have replaced the sbt.py file in the ~/lldb directory, use the Reload_script you created in chapter 19th to reload the commands in ~/.lldbinit.<br>Check if LLDB is correctly identified except for the SBT command:</p></p><p><p>(lldb) Help SBT<br>If Lldb identifies this command, you will get some help Information. This will be the starting point for the SBT command.<br>Open this file and jump to Generateexecutablemethodsscript. Here are some interesting things to point Out.<br>Do you remember how I noticed that Lldb.value was so slow in the previous chapters? If you are looking at a huge executable file that contains many methods, python checks that the time for each value in Nsdictionary will be forever.<br>instead, you don't need to grab a reference to every function in the Nsdictionary. All you need to do is grab the starting position of each function in the stack Record.</p></p><p><p>def Generateexecutablemethodsscript (frame_addresses):<br>Frame_addr_str = ' Nsarray *ar = @['<br>For F in Frame_addresses:<br>Frame_addr_str + = ' @ ' + str (f) + ' ", '<br>Frame_addr_str = frame_addr_str[:-1]<br>Frame_addr_str + = ']; '</p></p><pre><pre><code># Truncated content...# #############################command_script += frame_addr_strcommand_script += r‘‘‘</code></pre></pre><p><p>Nsmutabledictionary <em>stackdict = [nsmutabledictionary dictionary];<br>[retdict keysofentriespassingtest:^bool (id key, ID obj, BOOL </em>stop) {<br>If ([ar containsobject:key]) {<br>[stackdict Setobject:obj forkey:key];<br>Return YES;<br>}<br>Return NO;<br>}];<br>stackdict;<br>‘‘‘<br>Return Command_script<br>This is a sweet optimization, because instead of evaluating thousands of objective-c methods, you only need no more than 20 keys or a nsdictionary, or just the number of synthetic functions inside the stack Frame.<br>As the symbol breakpoint is still active and the program is paused, run the Script. Only a normal stack frame with no logic to re-symbolize the symbol will be printed.<br>It's time to make a little change to fix the Problem.</p></p><p><p>Implement the Code</p></p><p><p>The JIT code is already set up. All you need to do is call it and then compare the returned nsdictionary with any of the synthetic Sbvalues.<br>In processstacktracestringfromaddresses, search for the following comment:</p></p>New content Start 1New content End 1<p><p>Paste your new code here to call the JIT code to generate a list of potential methods in the Nsdictionary.</p></p>New Content Start 1<p><p>Methods = Target. EvaluateExpression (script, generateoptions ())<br>Methodsval = Lldb.value (methods.deref)</p></p>New Content End 1<p><p>You have called the code that returns nsdictionary and assigned it to the methods of the Sbvalue instance Variable.<br>You can transfer sbvalue to Lldb.value (technically He's just a value, but you might be confused if I don't have a module here) and copy it to the variable methodsval.<br>Now to the last part of the Python Code. All you need to do is check whether a sbframe Sbsymbol is synthesized and then execute the corresponding LOGIC.<br>In Processstacktracestringfromaddresses: further search for the following code:</p></p>New Content Start 2<p><p>Name = Symbol.name</p></p>New Content End 2<p><p>Change this part to look like this:</p></p>New Content Start 2<p><p>If Symbol.synthetic: # 1<br>Children = MethodsVal.sbvalue.GetNumChildren () # 2<br>Name = Symbol.name + R ' ... unresolved womp womp ' # 3<br>LoadAddr = symbol.addr.GetLoadAddress (target) # 4<br>For I in range (children):<br>Key = Long (methodsval[i].key.sbvalue.description) # 5<br>If key = = Loadaddr:<br>name = methodsval[i].value.sbvalue.description # 6<br>Break<br>Else<br>name = symbol.name # 7</p></p>New Content End 2<p><p>Offset_str = ' '<br>This part of the disassembly is as Follows:</p></p><p><p>You have enumerated these frames that occur outside this block of Code. For each symbol, a check is performed to see if the symbol is SYNTHETIC. If it is synthesized, his memory address will be compared to the address we collected in the Nsdictionary.<br>This will crawl the number of subclasses in the Objective-c class list that are matched to Lldb.value.<br>It doesn't matter, a valid reference to a name variable in the stack record needs to be generated and displayed. You're going to say you know this is a synthetic function, but the solution fails if your coming logic produces a result.<br>This gets the address of the composite function in memory in Question.<br>The key value given by Lldb.value is essentially from nsnumber, so you need to grab the description of this method and copy it to a number. it is confusing that it also assigns a Python variable called key.<br>If the key variable is equal to loadaddr, then you are matched to a Value. Assigns the name variable to the description of the variable in Nsdictionary.<br>That should be it. Save your results and then use Reload_script to reload your lldb content and try to run it.<br>Suppose you are still under the scheme of stripped shades of ray and pausing at a symbolic breakpoint that is only triggered when the UIView initwithframe: off use, Run the SBT command in the debugger to see if the first and third frames that were not available are Readable.<br>Frame #0:0x1053fe694 UIKit <code>-[UIView initWithFrame:]<br/>frame #1: 0x103cf53ac ShadesOfRay</code> -[rayview initwithframe:] + 924<br>Frame #2:0x1053fdda2 UIKit <code>-[UIView init] + 62<br/>frame #3: 0x103cf45bf ShadesOfRay</code> -[viewcontroller<br>Generaterayviewtapped:] + 79<br>It's so beautiful!</p></p><p><p>Why are we learning this?</p></p><p><p>Congratulations! you have successfully re-symbolized a streamlined two-mechanism file with the Objective-c runtime! What you can do with the right objective-c application is just Crazy.<br>There are still a few vulnerabilities in this script. This script is not able to support Objective-c's blocks Well. however, A careful study of how blocks is implemented and the Python module that browses lldb may reveal a way to indicate a objective-c block function that has been streamlined.<br>In addition, this script does not support the release mode iOS executable File. LLDB does not find a function that synthesizes the starting address of the Sbsymbol reference. This means that in the ARM64 compilation you will have to manually search up until you stumble through a assembly instruction that looks at the starting position of the Ali function (can you guess the command you are looking for?).<br>If you are not interested in the expansion of these scripts, try to figure out if you re-symbolize the Swift executable File. This challenge will certainly give you a big boost, but it still belongs to the range of things that lldb can do.<br>I wish you happy!</p></p><p><p>Advanced+apple+debugging (13)</p></p></span>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.