|
| 1 | +# macOS GCD - Grand Central Dispatch |
| 2 | + |
| 3 | +<details> |
| 4 | + |
| 5 | +<summary><a href="https://cloud.hacktricks.xyz/pentesting-cloud/pentesting-cloud-methodology"><strong>☁️ HackTricks Cloud ☁️</strong></a> -<a href="https://twitter.com/hacktricks_live"><strong>🐦 Twitter 🐦</strong></a> - <a href="https://www.twitch.tv/hacktricks_live/schedule"><strong>🎙️ Twitch 🎙️</strong></a> - <a href="https://www.youtube.com/@hacktricks_LIVE"><strong>🎥 Youtube 🎥</strong></a></summary> |
| 6 | + |
| 7 | +* Do you work in a **cybersecurity company**? Do you want to see your **company advertised in HackTricks**? or do you want to have access to the **latest version of the PEASS or download HackTricks in PDF**? Check the [**SUBSCRIPTION PLANS**](https://github.com/sponsors/carlospolop)! |
| 8 | +* Discover [**The PEASS Family**](https://opensea.io/collection/the-peass-family), our collection of exclusive [**NFTs**](https://opensea.io/collection/the-peass-family) |
| 9 | +* Get the [**official PEASS & HackTricks swag**](https://peass.creator-spring.com) |
| 10 | +* **Join the** [**💬**](https://emojipedia.org/speech-balloon/) [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** me on **Twitter** [**🐦**](https://github.com/carlospolop/hacktricks/tree/7af18b62b3bdc423e11444677a6a73d4043511e9/\[https:/emojipedia.org/bird/README.md)[**@carlospolopm**](https://twitter.com/hacktricks\_live)**.** |
| 11 | +* **Share your hacking tricks by submitting PRs to the** [**hacktricks repo**](https://github.com/carlospolop/hacktricks) **and** [**hacktricks-cloud repo**](https://github.com/carlospolop/hacktricks-cloud). |
| 12 | + |
| 13 | +</details> |
| 14 | + |
| 15 | +## Basic Information |
| 16 | + |
| 17 | +**Grand Central Dispatch (GCD),** also known as **libdispatch**, is available in both macOS and iOS. It's a technology developed by Apple to optimize application support for concurrent (multithreaded) execution on multicore hardware. |
| 18 | + |
| 19 | +**GCD** provides and manages **FIFO queues** to which your application can **submit tasks** in the form of **block objects**. Blocks submitted to dispatch queues are **executed on a pool of threads** fully managed by the system. GCD automatically creates threads for executing the tasks in the dispatch queues and schedules those tasks to run on the available cores. |
| 20 | + |
| 21 | +{% hint style="success" %} |
| 22 | +In summary, to execute code in **parallel**, processes can send **blocks of code to GCD**, which will take care of their execution. Therefore, processes don't create new threads; **GCD executes the given code with its own pool of threads**. |
| 23 | +{% endhint %} |
| 24 | + |
| 25 | +This is very helpful to manage parallel execution successfully, greatly reducing the number of threads processes create and optimising the parallel execution. This is idea for tasks that require **great parallelism** (brute-forcing?) or for tasks that shouldn't block the main thread: For example, the main thread on iOS handles UI interactions, so any other functionality that could make the app hang (searching, accessing a web, reading a file...) is managed this way. |
| 26 | + |
| 27 | +## Objective-C |
| 28 | + |
| 29 | +In Objetive-C there are different functions to send a block to be executed in parallel: |
| 30 | + |
| 31 | +* [**dispatch\_async**](https://developer.apple.com/documentation/dispatch/1453057-dispatch\_async): Submits a block for asynchronous execution on a dispatch queue and returns immediately. |
| 32 | +* [**dispatch\_sync**](https://developer.apple.com/documentation/dispatch/1452870-dispatch\_sync): Submits a block object for execution and returns after that block finishes executing. |
| 33 | +* [**dispatch\_once**](https://developer.apple.com/documentation/dispatch/1447169-dispatch\_once): Executes a block object only once for the lifetime of an application. |
| 34 | +* [**dispatch\_async\_and\_wait**](https://developer.apple.com/documentation/dispatch/3191901-dispatch\_async\_and\_wait): Submits a work item for execution and returns only after it finishes executing. Unlike [**`dispatch_sync`**](https://developer.apple.com/documentation/dispatch/1452870-dispatch\_sync), this function respects all attributes of the queue when it executes the block. |
| 35 | + |
| 36 | +These functions expect these parameters: [**`dispatch_queue_t`**](https://developer.apple.com/documentation/dispatch/dispatch\_queue\_t) **`queue,`** [**`dispatch_block_t`**](https://developer.apple.com/documentation/dispatch/dispatch\_block\_t) **`block`** |
| 37 | + |
| 38 | +This is the **struct of a Block**: |
| 39 | + |
| 40 | +```c |
| 41 | +struct Block { |
| 42 | + void *isa; // NSConcreteStackBlock,... |
| 43 | + int flags; |
| 44 | + int reserved; |
| 45 | + void *invoke; |
| 46 | + struct BlockDescriptor *descriptor; |
| 47 | + // captured variables go here |
| 48 | +}; |
| 49 | +``` |
| 50 | + |
| 51 | +And this is an example to use **parallelism** with **`dispatch_async`**: |
| 52 | + |
| 53 | +```objectivec |
| 54 | +#import <Foundation/Foundation.h> |
| 55 | + |
| 56 | +// Define a block |
| 57 | +void (^backgroundTask)(void) = ^{ |
| 58 | + // Code to be executed in the background |
| 59 | + for (int i = 0; i < 10; i++) { |
| 60 | + NSLog(@"Background task %d", i); |
| 61 | + sleep(1); // Simulate a long-running task |
| 62 | + } |
| 63 | +}; |
| 64 | + |
| 65 | +int main(int argc, const char * argv[]) { |
| 66 | + @autoreleasepool { |
| 67 | + // Create a dispatch queue |
| 68 | + dispatch_queue_t backgroundQueue = dispatch_queue_create("com.example.backgroundQueue", NULL); |
| 69 | + |
| 70 | + // Submit the block to the queue for asynchronous execution |
| 71 | + dispatch_async(backgroundQueue, backgroundTask); |
| 72 | + |
| 73 | + // Continue with other work on the main queue or thread |
| 74 | + for (int i = 0; i < 10; i++) { |
| 75 | + NSLog(@"Main task %d", i); |
| 76 | + sleep(1); // Simulate a long-running task |
| 77 | + } |
| 78 | + } |
| 79 | + return 0; |
| 80 | +} |
| 81 | +``` |
| 82 | +
|
| 83 | +## Swift |
| 84 | +
|
| 85 | +**`libswiftDispatch`** is a library that provides **Swift bindings** to the Grand Central Dispatch (GCD) framework which is originally written in C.\ |
| 86 | +The **`libswiftDispatch`** library wraps the C GCD APIs in a more Swift-friendly interface, making it easier and more intuitive for Swift developers to work with GCD. |
| 87 | +
|
| 88 | +* **`DispatchQueue.global().sync{ ... }`** |
| 89 | +* **`DispatchQueue.global().async{ ... }`** |
| 90 | +* **`let onceToken = DispatchOnce(); onceToken.perform { ... }`** |
| 91 | +* **`async await`** |
| 92 | + * **`var (data, response) = await URLSession.shared.data(from: URL(string: "https://api.example.com/getData"))`** |
| 93 | +
|
| 94 | +**Code example**: |
| 95 | +
|
| 96 | +```swift |
| 97 | +import Foundation |
| 98 | +
|
| 99 | +// Define a closure (the Swift equivalent of a block) |
| 100 | +let backgroundTask: () -> Void = { |
| 101 | + for i in 0..<10 { |
| 102 | + print("Background task \(i)") |
| 103 | + sleep(1) // Simulate a long-running task |
| 104 | + } |
| 105 | +} |
| 106 | +
|
| 107 | +// Entry point |
| 108 | +autoreleasepool { |
| 109 | + // Create a dispatch queue |
| 110 | + let backgroundQueue = DispatchQueue(label: "com.example.backgroundQueue") |
| 111 | + |
| 112 | + // Submit the closure to the queue for asynchronous execution |
| 113 | + backgroundQueue.async(execute: backgroundTask) |
| 114 | + |
| 115 | + // Continue with other work on the main queue |
| 116 | + for i in 0..<10 { |
| 117 | + print("Main task \(i)") |
| 118 | + sleep(1) // Simulate a long-running task |
| 119 | + } |
| 120 | +} |
| 121 | +``` |
| 122 | + |
| 123 | +## Frida |
| 124 | + |
| 125 | +The following Frida script can be used to **hook into several `dispatch`** functions and extract the queue name, the backtrace and the block: [**https://github.com/seemoo-lab/frida-scripts/blob/main/scripts/libdispatch.js**](https://github.com/seemoo-lab/frida-scripts/blob/main/scripts/libdispatch.js) |
| 126 | + |
| 127 | +```bash |
| 128 | +frida -U <prog_name> -l libdispatch.js |
| 129 | + |
| 130 | +dispatch_sync |
| 131 | +Calling queue: com.apple.UIKit._UIReusePool.reuseSetAccess |
| 132 | +Callback function: 0x19e3a6488 UIKitCore!__26-[_UIReusePool addObject:]_block_invoke |
| 133 | +Backtrace: |
| 134 | +0x19e3a6460 UIKitCore!-[_UIReusePool addObject:] |
| 135 | +0x19e3a5db8 UIKitCore!-[UIGraphicsRenderer _enqueueContextForReuse:] |
| 136 | +0x19e3a57fc UIKitCore!+[UIGraphicsRenderer _destroyCGContext:withRenderer:] |
| 137 | +[...] |
| 138 | +``` |
| 139 | + |
| 140 | +## Ghidra |
| 141 | + |
| 142 | +Currently Ghidra doesn't understand neither the ObjectiveC **`dispatch_block_t`** structure, neither the **`swift_dispatch_block`** one. |
| 143 | + |
| 144 | +So if you want it to understand them, you could just **declare them**: |
| 145 | + |
| 146 | +<figure><img src="../../.gitbook/assets/image (688).png" alt="" width="563"><figcaption></figcaption></figure> |
| 147 | + |
| 148 | +<figure><img src="../../.gitbook/assets/image (690).png" alt="" width="563"><figcaption></figcaption></figure> |
| 149 | + |
| 150 | +<figure><img src="../../.gitbook/assets/image (691).png" alt="" width="563"><figcaption></figcaption></figure> |
| 151 | + |
| 152 | +Then, find a place in the code where they are **used**: |
| 153 | + |
| 154 | +<figure><img src="../../.gitbook/assets/image (692).png" alt="" width="563"><figcaption></figcaption></figure> |
| 155 | + |
| 156 | +Right click on the variable -> Retype Variable and select in this case **`swift_dispatch_block`**: |
| 157 | + |
| 158 | +<figure><img src="../../.gitbook/assets/image (693).png" alt="" width="563"><figcaption></figcaption></figure> |
| 159 | + |
| 160 | +Ghidra will automatically rewrite everything: |
| 161 | + |
| 162 | +<figure><img src="../../.gitbook/assets/image (694).png" alt="" width="563"><figcaption></figcaption></figure> |
| 163 | + |
| 164 | +<details> |
| 165 | + |
| 166 | +<summary><a href="https://cloud.hacktricks.xyz/pentesting-cloud/pentesting-cloud-methodology"><strong>☁️ HackTricks Cloud ☁️</strong></a> -<a href="https://twitter.com/hacktricks_live"><strong>🐦 Twitter 🐦</strong></a> - <a href="https://www.twitch.tv/hacktricks_live/schedule"><strong>🎙️ Twitch 🎙️</strong></a> - <a href="https://www.youtube.com/@hacktricks_LIVE"><strong>🎥 Youtube 🎥</strong></a></summary> |
| 167 | + |
| 168 | +* Do you work in a **cybersecurity company**? Do you want to see your **company advertised in HackTricks**? or do you want to have access to the **latest version of the PEASS or download HackTricks in PDF**? Check the [**SUBSCRIPTION PLANS**](https://github.com/sponsors/carlospolop)! |
| 169 | +* Discover [**The PEASS Family**](https://opensea.io/collection/the-peass-family), our collection of exclusive [**NFTs**](https://opensea.io/collection/the-peass-family) |
| 170 | +* Get the [**official PEASS & HackTricks swag**](https://peass.creator-spring.com) |
| 171 | +* **Join the** [**💬**](https://emojipedia.org/speech-balloon/) [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** me on **Twitter** [**🐦**](https://github.com/carlospolop/hacktricks/tree/7af18b62b3bdc423e11444677a6a73d4043511e9/\[https:/emojipedia.org/bird/README.md)[**@carlospolopm**](https://twitter.com/hacktricks\_live)**.** |
| 172 | +* **Share your hacking tricks by submitting PRs to the** [**hacktricks repo**](https://github.com/carlospolop/hacktricks) **and** [**hacktricks-cloud repo**](https://github.com/carlospolop/hacktricks-cloud). |
| 173 | + |
| 174 | +</details> |
0 commit comments