Difference between revisions of "MobileDevice Library"

From The iPhone Wiki
Jump to: navigation, search
(MobileDevice Header (mobiledevice.h))
 
(85 intermediate revisions by 26 users not shown)
Line 1: Line 1:
  +
{{float toc|right}}
MobileDevice Library is used by itunes to transfer data betwen iPhone and computer, connexion over the USB port.
 
  +
MobileDevice Library is used by [[iTunes]] to transfer data between iPhone and computer over both USB and WiFi connections.
   
===PC Windows : iTunesMobileDevice.dll===
+
=== Windows: iTunesMobileDevice.dll ===
  +
* Location: <code>C:\Program Files\Common Files\Apple\Mobile Device Support\iTunesMobileDevice.dll</code> (<code>Program Files (x86)</code> on 64-bit)
  +
* Supporting CoreFoundation.dll (used for CFStringRef, CFPropertyListRef management) is located in the same dir (when using [[iTunes]] prior 9.0).
  +
* For [[iTunes]] 9.0, the location of CoreFoundation.dll is stored in '''InstallDir''' registry value under '''HKLM\SOFTWARE\Apple Inc.\Apple Application Support''' registry key.
   
  +
=== Mac OS X: MobileDevice.framework ===
* Location : C:\Program Files\Common Files\Apple\Mobile Device Support\bin\iTunesMobileDevice.dll
 
  +
* Location: /System/Library/PrivateFrameworks/MobileDevice.framework
* Export : [[itunesmobiledevice.dll]]
 
  +
* Export command: <code>nm /System/Library/PrivateFrameworks/MobileDevice.framework/Versions/A/MobileDevice</code>
   
  +
=== Library Interfaces ===
===Mac OSX : MobileDevice.framework===
 
  +
* [http://www.libimobiledevice.org/ libimobiledevice] (provides the same functionality on GNU/Linux)
  +
* [https://github.com/imkira/mobiledevice mobiledevice] (command line utility for interacting with MobileDevice Framework)
  +
* [https://github.com/samdmarshall/SDMMobileDevice SDMMobileDevice] (OS X framework written in C that can be used interchangeably with Apple's private framework MobileDevice.framework)
  +
* [https://bitbucket.org/tristero/mobiledeviceaccess MobileDeviceAccess] (similar to above, but written in Objective-C)
  +
* [http://samdmarshall.com/media/MobileDevice.h MobileDevice.h] (old reverse engineered header for interfacing with MobileDevice library)
   
* Location : /System/Library/PrivateFrameworks/MobileDevice.framework
 
* Export command : "nm /System/Library/PrivateFrameworks/MobileDevice.framework/Versions/A/MobileDevice"
 
   
===MobileDevice Header (mobiledevice.h)===
 
   
  +
=== Private Functions ===
Reversed engineering C header for MobileDevice Library.
 
   
  +
==== Obtaining address ====
<pre>
 
  +
In order to obtain the address of a usable private function in MobileDevice, you will have to be able to understand x86-64 assembly to reverse engineer it. These methods differ slightly based on platform due to how dynamically linked libraries handle position independent code.
/* ----------------------------------------------------------------------------
 
* MobileDevice.h - interface to MobileDevice.framework
 
* ------------------------------------------------------------------------- */
 
#pragma once
 
   
  +
=====Mac OS X (MobileDevice.framework)=====
#ifndef MOBILEDEVICE_H
 
  +
A private function is not marked as exported in the mach-o symbol table. This means it cannot be called by simply linking against the library. To call unexported functions, the mach-o symbol table must be stepped through manually to find the offset of a particular function call. Calls can be verified by checking against the offset of the name inside the name table.
#define MOBILEDEVICE_H
 
   
  +
=====Windows (MobileDevice.dll)=====
#ifdef __cplusplus
 
  +
Unlike OS X's dynamically linkable libraries, Windows dynamic libraries do not support position independent code in the same manner. A private function will not have its name in the exported symbol table, so in a debugger, like GDB, it will show up as part of another function. However, you will know that it is a separate function as a new stack frame is set up.
extern "C" {
 
#endif
 
 
#ifndef __GCC__
 
#pragma pack
 
#define __PACK
 
#else
 
#define __PACK __attribute__((__packed__))
 
#endif
 
   
#if defined(WIN32)
 
#define __DLLIMPORT [DllImport("iTunesMobileDevice.dll")]
 
using namespace System::Runtime::InteropServices;
 
#include <CoreFoundation.h>
 
typedef unsigned int mach_error_t;
 
#elif defined(__APPLE__)
 
#define __DLLIMPORT
 
#include <CoreFoundation/CoreFoundation.h>
 
#include <mach/error.h>
 
#endif
 
 
/* Error codes */
 
#define MDERR_APPLE_MOBILE (err_system(0x3a))
 
#define MDERR_IPHONE (err_sub(0))
 
 
/* Apple Mobile (AM*) errors */
 
#define MDERR_OK ERR_SUCCESS
 
#define MDERR_SYSCALL (ERR_MOBILE_DEVICE | 0x01)
 
#define MDERR_OUT_OF_MEMORY (ERR_MOBILE_DEVICE | 0x03)
 
#define MDERR_QUERY_FAILED (ERR_MOBILE_DEVICE | 0x04)
 
#define MDERR_INVALID_ARGUMENT (ERR_MOBILE_DEVICE | 0x0b)
 
#define MDERR_DICT_NOT_LOADED (ERR_MOBILE_DEVICE | 0x25)
 
 
/* Apple File Connection (AFC*) errors */
 
#define MDERR_AFC_OUT_OF_MEMORY 0x03
 
 
/* USBMux errors */
 
#define MDERR_USBMUX_ARG_NULL 0x16
 
#define MDERR_USBMUX_FAILED 0xffffffff
 
 
/* Messages passed to device notification callbacks: passed as part of
 
* am_device_notification_callback_info. */
 
#define ADNCI_MSG_CONNECTED 1
 
#define ADNCI_MSG_DISCONNECTED 2
 
#define ADNCI_MSG_UNSUBSCRIBED 3
 
 
#define AMD_IPHONE_PRODUCT_ID 0x1290
 
//#define AMD_IPHONE_SERIAL ""
 
 
/* Services, found in /System/Library/Lockdown/Services.plist */
 
#define AMSVC_AFC CFSTR("com.apple.afc")
 
#define AMSVC_BACKUP CFSTR("com.apple.mobilebackup")
 
#define AMSVC_CRASH_REPORT_COPY CFSTR("com.apple.crashreportcopy")
 
#define AMSVC_DEBUG_IMAGE_MOUNT CFSTR("com.apple.mobile.debug_image_mount")
 
#define AMSVC_NOTIFICATION_PROXY CFSTR("com.apple.mobile.notification_proxy")
 
#define AMSVC_PURPLE_TEST CFSTR("com.apple.purpletestr")
 
#define AMSVC_SOFTWARE_UPDATE CFSTR("com.apple.mobile.software_update")
 
#define AMSVC_SYNC CFSTR("com.apple.mobilesync")
 
#define AMSVC_SCREENSHOT CFSTR("com.apple.screenshotr")
 
#define AMSVC_SYSLOG_RELAY CFSTR("com.apple.syslog_relay")
 
#define AMSVC_SYSTEM_PROFILER CFSTR("com.apple.mobile.system_profiler")
 
 
typedef unsigned int afc_error_t;
 
typedef unsigned int usbmux_error_t;
 
 
struct am_recovery_device;
 
 
struct am_device_notification_callback_info {
 
struct am_device *dev; /* 0 device */
 
unsigned int msg; /* 4 one of ADNCI_MSG_* */
 
struct am_device_notification* subscription;
 
} __PACK;
 
 
/* The type of the device restore notification callback functions.
 
* TODO: change to correct type. */
 
typedef void (*am_restore_device_notification_callback)(struct am_recovery_device *);
 
 
/* This is a CoreFoundation object of class AMRecoveryModeDevice. */
 
struct am_recovery_device {
 
unsigned char unknown0[8]; /* 0 */
 
am_restore_device_notification_callback callback; /* 8 */
 
void *user_info; /* 12 */
 
unsigned char unknown1[12]; /* 16 */
 
unsigned int readwrite_pipe; /* 28 */
 
unsigned char read_pipe; /* 32 */
 
unsigned char write_ctrl_pipe; /* 33 */
 
unsigned char read_unknown_pipe; /* 34 */
 
unsigned char write_file_pipe; /* 35 */
 
unsigned char write_input_pipe; /* 36 */
 
} __PACK;
 
 
/* A CoreFoundation object of class AMRestoreModeDevice. */
 
struct am_restore_device {
 
unsigned char unknown[32];
 
int port;
 
} __PACK;
 
 
/* The type of the device notification callback function. */
 
typedef void(*am_device_notification_callback)(struct am_device_notification_callback_info *, int cookie);
 
 
/* The type of the _AMDDeviceAttached function.
 
* TODO: change to correct type. */
 
typedef void *amd_device_attached_callback;
 
 
/* The type of the device restore notification callback functions.
 
* TODO: change to correct type. */
 
typedef void (*am_restore_device_notification_callback)(struct am_recovery_device *);
 
   
/* Structure that contains internal data used by AMDevice... functions. Never try
 
* to access its members directly! Use AMDeviceCopyDeviceIdentifier,
 
* AMDeviceGetConnectionID, AMDeviceRetain, AMDeviceRelease instead. */
 
struct am_device {
 
unsigned char unknown0[16]; /* 0 - zero */
 
unsigned int device_id; /* 16 */
 
unsigned int product_id; /* 20 - set to AMD_IPHONE_PRODUCT_ID */
 
char *serial; /* 24 - set to UDID, Unique Device Identifier */
 
unsigned int unknown1; /* 28 */
 
unsigned int unknown2; /* 32 - reference counter, increased by AMDeviceRetain, decreased by AMDeviceRelease*/
 
unsigned int lockdown_conn; /* 36 */
 
unsigned char unknown3[8]; /* 40 */
 
#if (__ITUNES_VER > 740)
 
unsigned int unknown4; /* 48 - used to store CriticalSection Handle*/
 
#endif
 
#if (__ITUNES_VER >= 800)
 
unsigned char unknown5[24]; /* 52 */
 
#endif
 
} __PACK;
 
 
struct am_device_notification {
 
unsigned int unknown0; /* 0 */
 
unsigned int unknown1; /* 4 */
 
unsigned int unknown2; /* 8 */
 
am_device_notification_callback callback; /* 12 */
 
unsigned int cookie; /* 16 */
 
} __PACK;
 
 
struct afc_connection {
 
unsigned int handle; /* 0 */
 
unsigned int unknown0; /* 4 */
 
unsigned char unknown1; /* 8 */
 
unsigned char padding[3]; /* 9 */
 
unsigned int unknown2; /* 12 */
 
unsigned int unknown3; /* 16 */
 
unsigned int unknown4; /* 20 */
 
unsigned int fs_block_size; /* 24 */
 
unsigned int sock_block_size; /* 28: always 0x3c */
 
unsigned int io_timeout; /* 32: from AFCConnectionOpen, usu. 0 */
 
void *afc_lock; /* 36 */
 
unsigned int context; /* 40 */
 
} __PACK;
 
 
 
   
  +
=== Known Error Codes ===
struct afc_device_info {
 
  +
* kAMDSuccess = 0x0
unsigned char unknown[12]; /* 0 */
 
  +
* kAMDUndefinedError = 0xe8000001
} __PACK;
 
  +
* kAMDBadHeaderError = 0xe8000002
  +
* kAMDNoResourcesError = 0xe8000003
  +
* kAMDReadError = 0xe8000004
  +
* kAMDWriteError = 0xe8000005
  +
* kAMDUnknownPacketError = 0xe8000006
  +
* kAMDInvalidArgumentError = 0xe8000007
  +
* kAMDNotFoundError = 0xe8000008
  +
* kAMDIsDirectoryError = 0xe8000009
  +
* kAMDPermissionError = 0xe800000a
  +
* kAMDNotConnectedError = 0xe800000b
  +
* kAMDTimeOutError = 0xe800000c
  +
* kAMDOverrunError = 0xe800000d
  +
* kAMDEOFError = 0xe800000e
  +
* kAMDUnsupportedError = 0xe800000f
  +
* kAMDFileExistsError = 0xe8000010
  +
* kAMDBusyError = 0xe8000011
  +
* kAMDCryptoError = 0xe8000012
  +
* kAMDInvalidResponseError = 0xe8000013
  +
* kAMDMissingKeyError = 0xe8000014
  +
* kAMDMissingValueError = 0xe8000015
  +
* kAMDGetProhibitedError = 0xe8000016
  +
* kAMDSetProhibitedError = 0xe8000017
  +
* kAMDRemoveProhibitedError = 0xe8000018
  +
* kAMDImmutableValueError = 0xe8000019
  +
* kAMDPasswordProtectedError = 0xe800001a
  +
* kAMDMissingHostIDError = 0xe800001b
  +
* kAMDInvalidHostIDError = 0xe800001c
  +
* kAMDSessionActiveError = 0xe800001d
  +
* kAMDSessionInactiveError = 0xe800001e
  +
* kAMDMissingSessionIDError = 0xe800001f
  +
* kAMDInvalidSessionIDError = 0xe8000020
  +
* kAMDMissingServiceError = 0xe8000021
  +
* kAMDInvalidServiceError = 0xe8000022
  +
* kAMDInvalidCheckinError = 0xe8000023
  +
* kAMDCheckinTimeoutError = 0xe8000024
  +
* kAMDMissingPairRecordError = 0xe8000025
  +
* kAMDInvalidActivationRecordError = 0xe8000026
  +
* kAMDMissingActivationRecordError = 0xe8000027
  +
* kAMDWrongDroidError = 0xe8000028
  +
* kAMDSUVerificationError = 0xe8000029
  +
* kAMDSUPatchError = 0xe800002a
  +
* kAMDSUFirmwareError = 0xe800002b
  +
* kAMDProvisioningProfileNotValid = 0xe800002c
  +
* kAMDSendMessageError = 0xe800002d
  +
* kAMDReceiveMessageError = 0xe800002e
  +
* kAMDMissingOptionsError = 0xe800002f
  +
* kAMDMissingImageTypeError = 0xe8000030
  +
* kAMDDigestFailedError = 0xe8000031
  +
* kAMDStartServiceError = 0xe8000032
  +
* kAMDInvalidDiskImageError = 0xe8000033
  +
* kAMDMissingDigestError = 0xe8000034
  +
* kAMDMuxError = 0xe8000035
  +
* kAMDApplicationAlreadyInstalledError = 0xe8000036
  +
* kAMDApplicationMoveFailedError = 0xe8000037
  +
* kAMDApplicationSINFCaptureFailedError = 0xe8000038
  +
* kAMDApplicationSandboxFailedError = 0xe8000039
  +
* kAMDApplicationVerificationFailedError = 0xe800003a
  +
* kAMDArchiveDestructionFailedError = 0xe800003b
  +
* kAMDBundleVerificationFailedError = 0xe800003c
  +
* kAMDCarrierBundleCopyFailedError = 0xe800003d
  +
* kAMDCarrierBundleDirectoryCreationFailedError = 0xe800003e
  +
* kAMDCarrierBundleMissingSupportedSIMsError = 0xe800003f
  +
* kAMDCommCenterNotificationFailedError = 0xe8000040
  +
* kAMDContainerCreationFailedError = 0xe8000041
  +
* kAMDContainerP0wnFailedError = 0xe8000042
  +
* kAMDContainerRemovalFailedError = 0xe8000043
  +
* kAMDEmbeddedProfileInstallFailedError = 0xe8000044
  +
* kAMDErrorError = 0xe8000045
  +
* kAMDExecutableTwiddleFailedError = 0xe8000046
  +
* kAMDExistenceCheckFailedError = 0xe8000047
  +
* kAMDInstallMapUpdateFailedError = 0xe8000048
  +
* kAMDManifestCaptureFailedError = 0xe8000049
  +
* kAMDMapGenerationFailedError = 0xe800004a
  +
* kAMDMissingBundleExecutableError = 0xe800004b
  +
* kAMDMissingBundleIdentifierError = 0xe800004c
  +
* kAMDMissingBundlePathError = 0xe800004d
  +
* kAMDMissingContainerError = 0xe800004e
  +
* kAMDNotificationFailedError = 0xe800004f
  +
* kAMDPackageExtractionFailedError = 0xe8000050
  +
* kAMDPackageInspectionFailedError = 0xe8000051
  +
* kAMDPackageMoveFailedError = 0xe8000052
  +
* kAMDPathConversionFailedError = 0xe8000053
  +
* kAMDRestoreContainerFailedError = 0xe8000054
  +
* kAMDSeatbeltProfileRemovalFailedError = 0xe8000055
  +
* kAMDStageCreationFailedError = 0xe8000056
  +
* kAMDSymlinkFailedError = 0xe8000057
  +
* kAMDiTunesArtworkCaptureFailedError = 0xe8000058
  +
* kAMDiTunesMetadataCaptureFailedError = 0xe8000059
  +
* kAMDAlreadyArchivedError = 0xe800005a
  +
* kAMDProhibitedBySupervision = 0xe8000083
   
  +
For the latest error codes you can look at the pseudo-code of AMDErrorString
struct afc_directory {
 
unsigned char unknown[0]; /* size unknown */
 
} __PACK;
 
 
struct afc_dictionary {
 
unsigned char unknown[0]; /* size unknown */
 
} __PACK;
 
 
typedef unsigned long long afc_file_ref;
 
 
struct usbmux_listener_1 { /* offset value in iTunes */
 
unsigned int unknown0; /* 0 1 */
 
unsigned char *unknown1; /* 4 ptr, maybe device? */
 
amd_device_attached_callback callback; /* 8 _AMDDeviceAttached */
 
unsigned int unknown3; /* 12 */
 
unsigned int unknown4; /* 16 */
 
unsigned int unknown5; /* 20 */
 
} __PACK;
 
 
struct usbmux_listener_2 {
 
unsigned char unknown0[4144];
 
} __PACK;
 
 
struct am_bootloader_control_packet {
 
unsigned char opcode; /* 0 */
 
unsigned char length; /* 1 */
 
unsigned char magic[2]; /* 2: 0x34, 0x12 */
 
unsigned char payload[0]; /* 4 */
 
} __PACK;
 
 
/* ----------------------------------------------------------------------------
 
* Public routines
 
* ------------------------------------------------------------------------- */
 
 
/* Registers a notification with the current run loop. The callback gets
 
* copied into the notification struct, as well as being registered with the
 
* current run loop. Cookie gets copied into cookie in the same.
 
* (Cookie is a user info parameter that gets passed as an arg to
 
* the callback) unused0 and unused1 are both 0 when iTunes calls this.
 
*
 
* Never try to acces directly or copy contents of dev and subscription fields
 
* in am_device_notification_callback_info. Treat them as abstract handles.
 
* When done with connection use AMDeviceRelease to free resources allocated for am_device.
 
*
 
* Returns:
 
* MDERR_OK if successful
 
* MDERR_SYSCALL if CFRunLoopAddSource() failed
 
* MDERR_OUT_OF_MEMORY if we ran out of memory
 
*/
 
__DLLIMPORT mach_error_t AMDeviceNotificationSubscribe(am_device_notification_callback callback,
 
unsigned int unused0, unsigned int unused1,
 
unsigned int cookie,
 
struct am_device_notification **subscription);
 
 
 
/* Unregisters notifications
 
*/
 
__DLLIMPORT mach_error_t AMDeviceNotificationUnsubscribe(am_device_notification* subscription);
 
 
/* Returns device_id field of am_device structure
 
*/
 
__DLLIMPORT unsigned int AMDeviceGetConnectionID(struct am_device *device);
 
 
/* Returns serial field of am_device structure
 
*/
 
__DLLIMPORT CFStringRef AMDeviceCopyDeviceIdentifier(struct am_device *device);
 
 
/* Connects to the iPhone. Pass in the am_device structure that the
 
* notification callback will give to you.
 
*
 
* Returns:
 
* MDERR_OK if successfully connected
 
* MDERR_SYSCALL if setsockopt() failed
 
* MDERR_QUERY_FAILED if the daemon query failed
 
* MDERR_INVALID_ARGUMENT if USBMuxConnectByPort returned 0xffffffff
 
*/
 
__DLLIMPORT mach_error_t AMDeviceConnect(struct am_device *device);
 
 
/* Calls PairingRecordPath() on the given device, than tests whether the path
 
* which that function returns exists. During the initial connect, the path
 
* returned by that function is '/', and so this returns 1.
 
*
 
* Returns:
 
* 0 if the path did not exist
 
* 1 if it did
 
*/
 
__DLLIMPORT mach_error_t AMDeviceIsPaired(struct am_device *device);
 
__DLLIMPORT mach_error_t AMDevicePair(struct am_device *device);
 
 
/* iTunes calls this function immediately after testing whether the device is
 
* paired. It creates a pairing file and establishes a Lockdown connection.
 
*
 
* Returns:
 
* MDERR_OK if successful
 
* MDERR_INVALID_ARGUMENT if the supplied device is null
 
* MDERR_DICT_NOT_LOADED if the load_dict() call failed
 
*/
 
__DLLIMPORT mach_error_t AMDeviceValidatePairing(struct am_device *device);
 
 
/* Creates a Lockdown session and adjusts the device structure appropriately
 
* to indicate that the session has been started. iTunes calls this function
 
* after validating pairing.
 
*
 
* Returns:
 
* MDERR_OK if successful
 
* MDERR_INVALID_ARGUMENT if the Lockdown conn has not been established
 
* MDERR_DICT_NOT_LOADED if the load_dict() call failed
 
*/
 
__DLLIMPORT mach_error_t AMDeviceStartSession(struct am_device *device);
 
 
/* Starts a service and returns a socket file descriptor that can be used in order to further
 
* access the service. You should stop the session and disconnect before using
 
* the service. iTunes calls this function after starting a session. It starts
 
* the service and the SSL connection. unknown may safely be
 
* NULL (it is when iTunes calls this), but if it is not, then it will be
 
* filled upon function exit. service_name should be one of the AMSVC_*
 
* constants.
 
*
 
* Returns:
 
* MDERR_OK if successful
 
* MDERR_SYSCALL if the setsockopt() call failed
 
* MDERR_INVALID_ARGUMENT if the Lockdown conn has not been established
 
*/
 
__DLLIMPORT mach_error_t AMDeviceStartService(struct am_device *device, CFStringRef
 
service_name, int *socket_fd, unsigned int *
 
unknown);
 
 
/* Stops a session. You should do this before accessing services.
 
*
 
* Returns:
 
* MDERR_OK if successful
 
* MDERR_INVALID_ARGUMENT if the Lockdown conn has not been established
 
*/
 
__DLLIMPORT mach_error_t AMDeviceStopSession(struct am_device *device);
 
 
/* Decrements reference counter and, if nothing left, releases resources hold
 
* by connection, invalidates pointer to device
 
*/
 
__DLLIMPORT void AMDeviceRelease(struct am_device *device);
 
 
/* Increments reference counter
 
*/
 
__DLLIMPORT void AMDeviceRetain(struct am_device *device);
 
 
/* Opens an Apple File Connection. You must start the appropriate service
 
* first with AMDeviceStartService(). In iTunes, io_timeout is 0.
 
*
 
* Returns:
 
* MDERR_OK if successful
 
* MDERR_AFC_OUT_OF_MEMORY if malloc() failed
 
*/
 
__DLLIMPORT afc_error_t AFCConnectionOpen(int socket_fd, unsigned int io_timeout,
 
struct afc_connection **conn);
 
 
/* Pass in a pointer to an afc_device_info structure. It will be filled. */
 
__DLLIMPORT afc_error_t AFCDeviceInfoOpen(struct afc_connection *conn, struct
 
afc_dictionary **info);
 
 
/* Turns debug mode on if the environment variable AFCDEBUG is set to a numeric
 
* value, or if the file '/AFCDEBUG' is present and contains a value. */
 
#if defined(__APPLE__)
 
void AFCPlatformInit();
 
#endif
 
 
/* Opens a directory on the iPhone. Pass in a pointer in dir to be filled in.
 
* Note that this normally only accesses the iTunes sandbox/partition as the
 
* root, which is /var/root/Media. Pathnames are specified with '/' delimiters
 
* as in Unix style.
 
*
 
* Returns:
 
* MDERR_OK if successful
 
*/
 
__DLLIMPORT afc_error_t AFCDirectoryOpen(struct afc_connection *conn, char *path, struct
 
afc_directory **dir);
 
 
/* Acquires the next entry in a directory previously opened with
 
* AFCDirectoryOpen(). When dirent is filled with a NULL value, then the end
 
* of the directory has been reached. '.' and '..' will be returned as the
 
* first two entries in each directory except the root; you may want to skip
 
* over them.
 
*
 
* Returns:
 
* MDERR_OK if successful, even if no entries remain
 
*/
 
__DLLIMPORT afc_error_t AFCDirectoryRead(struct afc_connection *conn/*unsigned int unused*/, struct afc_directory *dir,
 
char **dirent);
 
__DLLIMPORT afc_error_t AFCDirectoryClose(afc_connection *conn, struct afc_directory *dir);
 
__DLLIMPORT afc_error_t AFCDirectoryCreate(afc_connection *conn, char *dirname);
 
__DLLIMPORT afc_error_t AFCRemovePath(afc_connection *conn, char *dirname);
 
__DLLIMPORT afc_error_t AFCRenamePath(afc_connection *conn, char *oldpath, char *newpath);
 
 
/* Returns the context field of the given AFC connection. */
 
__DLLIMPORT unsigned int AFCConnectionGetContext(struct afc_connection *conn);
 
 
/* Returns the fs_block_size field of the given AFC connection. */
 
__DLLIMPORT unsigned int AFCConnectionGetFSBlockSize(struct afc_connection *conn);
 
 
/* Returns the io_timeout field of the given AFC connection. In iTunes this is
 
* 0. */
 
__DLLIMPORT unsigned int AFCConnectionGetIOTimeout(struct afc_connection *conn);
 
 
/* Returns the sock_block_size field of the given AFC connection. */
 
__DLLIMPORT unsigned int AFCConnectionGetSocketBlockSize(struct afc_connection *conn);
 
 
/* Closes the given AFC connection. */
 
__DLLIMPORT afc_error_t AFCConnectionClose(struct afc_connection *conn);
 
 
/* Registers for device notifications related to the restore process. unknown0
 
* is zero when iTunes calls this. In iTunes,
 
* the callbacks are located at:
 
* 1: $3ac68e-$3ac6b1, calls $3ac542(unknown1, arg, 0)
 
* 2: $3ac66a-$3ac68d, calls $3ac542(unknown1, 0, arg)
 
* 3: $3ac762-$3ac785, calls $3ac6b2(unknown1, arg, 0)
 
* 4: $3ac73e-$3ac761, calls $3ac6b2(unknown1, 0, arg)
 
*/
 
__DLLIMPORT unsigned int AMRestoreRegisterForDeviceNotifications(
 
am_restore_device_notification_callback dfu_connect_callback,
 
am_restore_device_notification_callback recovery_connect_callback,
 
am_restore_device_notification_callback dfu_disconnect_callback,
 
am_restore_device_notification_callback recovery_disconnect_callback,
 
unsigned int unknown0,
 
void *user_info);
 
 
/* Causes the restore functions to spit out (unhelpful) progress messages to
 
* the file specified by the given path. iTunes always calls this right before
 
* restoring with a path of
 
* "$HOME/Library/Logs/iPhone Updater Logs/iPhoneUpdater X.log", where X is an
 
* unused number.
 
*/
 
__DLLIMPORT unsigned int AMRestoreEnableFileLogging(char *path);
 
 
/* Initializes a new option dictionary to default values. Pass the constant
 
* kCFAllocatorDefault as the allocator. The option dictionary looks as
 
* follows:
 
* {
 
* NORImageType => 'production',
 
* AutoBootDelay => 0,
 
* KernelCacheType => 'Release',
 
* UpdateBaseband => true,
 
* DFUFileType => 'RELEASE',
 
* SystemImageType => 'User',
 
* CreateFilesystemPartitions => true,
 
* FlashNOR => true,
 
* RestoreBootArgs => 'rd=md0 nand-enable-reformat=1 -progress'
 
* BootImageType => 'User'
 
* }
 
*
 
* Returns:
 
* the option dictionary if successful
 
* NULL if out of memory
 
*/
 
__DLLIMPORT CFMutableDictionaryRef AMRestoreCreateDefaultOptions(CFAllocatorRef allocator);
 
 
/* ----------------------------------------------------------------------------
 
* Less-documented public routines
 
* ------------------------------------------------------------------------- */
 
 
/* mode 2 = read, mode 3 = write; unknown = 0 */
 
__DLLIMPORT afc_error_t AFCFileRefOpen(struct afc_connection *conn, char *path, unsigned
 
long long int mode, afc_file_ref *ref);
 
__DLLIMPORT afc_error_t AFCFileRefRead(struct afc_connection *conn, afc_file_ref ref,
 
void *buf, unsigned int *len);
 
__DLLIMPORT afc_error_t AFCFileRefWrite(struct afc_connection *conn, afc_file_ref ref,
 
void *buf, unsigned int len);
 
__DLLIMPORT afc_error_t AFCFileRefSeek(struct afc_connection *conn, afc_file_ref ref,
 
unsigned long long offset1, unsigned long long offset2);
 
__DLLIMPORT afc_error_t AFCFileRefLock(struct afc_connection *conn, afc_file_ref ref);
 
__DLLIMPORT afc_error_t AFCFileRefUnlock(struct afc_connection *conn, afc_file_ref ref);
 
__DLLIMPORT afc_error_t AFCFileRefClose(struct afc_connection *conn, afc_file_ref ref);
 
__DLLIMPORT afc_error_t AFCFileInfoOpen(struct afc_connection *conn, char *path, struct
 
afc_dictionary **info);
 
__DLLIMPORT afc_error_t AFCKeyValueRead(struct afc_dictionary *dict, char **key, char **
 
val);
 
__DLLIMPORT afc_error_t AFCKeyValueClose(struct afc_dictionary *dict);
 
__DLLIMPORT unsigned int AMRestorePerformRecoveryModeRestore(struct am_recovery_device *
 
rdev, CFDictionaryRef opts, void *callback, void *user_info);
 
__DLLIMPORT unsigned int AMRestorePerformRestoreModeRestore(struct am_restore_device *
 
rdev, CFDictionaryRef opts, void *callback, void *user_info);
 
__DLLIMPORT struct am_restore_device *AMRestoreModeDeviceCreate(unsigned int unknown0,
 
unsigned int connection_id, unsigned int unknown1);
 
__DLLIMPORT unsigned int AMRestoreCreatePathsForBundle(CFStringRef restore_bundle_path,
 
CFStringRef kernel_cache_type, CFStringRef boot_image_type, unsigned int
 
unknown0, CFStringRef *firmware_dir_path, CFStringRef *
 
kernelcache_restore_path, unsigned int unknown1, CFStringRef *
 
ramdisk_path);
 
__DLLIMPORT unsigned int AMRestoreModeDeviceReboot(struct am_restore_device *rdev); // Added by JB 30.07.2008
 
__DLLIMPORT mach_error_t AMDeviceEnterRecovery(struct am_device *device);
 
__DLLIMPORT mach_error_t AMDeviceDisconnect(struct am_device *device);
 
__DLLIMPORT CFStringRef AMDeviceCopyValue(struct am_device *device, unsigned int, CFStringRef cfstring)
 
/* to use this, start the service "com.apple.mobile.notification_proxy", handle will be the socket to use */
 
__DLLIMPORT mach_error_t AMDPostNotification(SOCKET socket, CFStringRef notification, CFStringRef userinfo);
 
__DLLIMPORT mach_error_t AMDShutdownNotificationProxy(SOCKET socket);
 
 
/*edits by geohot*/
 
__DLLIMPORT mach_error_t AMDeviceDeactivate(struct am_device *device);
 
__DLLIMPORT mach_error_t AMDeviceActivate(struct am_device *device, CFDictionaryRef dict);
 
__DLLIMPORT mach_error_t AMDeviceRemoveValue(struct am_device *device, unsigned int, CFStringRef cfstring);
 
 
/* ----------------------------------------------------------------------------
 
* Semi-private routines
 
* ------------------------------------------------------------------------- */
 
 
/* Pass in a usbmux_listener_1 structure and a usbmux_listener_2 structure
 
* pointer, which will be filled with the resulting usbmux_listener_2.
 
*
 
* Returns:
 
* MDERR_OK if completed successfully
 
* MDERR_USBMUX_ARG_NULL if one of the arguments was NULL
 
* MDERR_USBMUX_FAILED if the listener was not created successfully
 
*/
 
__DLLIMPORT usbmux_error_t USBMuxListenerCreate(struct usbmux_listener_1 *esi_fp8, struct
 
usbmux_listener_2 **eax_fp12);
 
 
/* ----------------------------------------------------------------------------
 
* Less-documented semi-private routines
 
* ------------------------------------------------------------------------- */
 
__DLLIMPORT usbmux_error_t USBMuxListenerHandleData(void *);
 
 
/* ----------------------------------------------------------------------------
 
* Private routines - here be dragons
 
* ------------------------------------------------------------------------- */
 
 
/* AMRestorePerformRestoreModeRestore() calls this function with a dictionary
 
* in order to perform certain special restore operations
 
* (RESTORED_OPERATION_*). It is thought that this function might enable
 
* significant access to the phone. */
 
 
/*
 
typedef unsigned int (*t_performOperation)(struct am_restore_device *rdev,
 
CFDictionaryRef op) __attribute__ ((regparm(2)));
 
t_performOperation _performOperation = (t_performOperation)0x3c39fa4b;
 
*/
 
 
/* ----------------------------------------------------------------------------
 
* Less-documented private routines
 
* ------------------------------------------------------------------------- */
 
 
 
/*
 
typedef int (*t_socketForPort)(struct am_restore_device *rdev, unsigned int port)
 
__attribute__ ((regparm(2)));
 
t_socketForPort _socketForPort = (t_socketForPort)(void *)0x3c39f36c;
 
 
typedef void (*t_restored_send_message)(int port, CFDictionaryRef msg);
 
t_restored_send_message _restored_send_message = (t_restored_send_message)0x3c3a4e40;
 
 
typedef CFDictionaryRef (*t_restored_receive_message)(int port);
 
t_restored_receive_message _restored_receive_message = (t_restored_receive_message)0x3c3a4d40;
 
 
typedef unsigned int (*t_sendControlPacket)(struct am_recovery_device *rdev, unsigned
 
int msg1, unsigned int msg2, unsigned int unknown0, unsigned int *unknown1,
 
unsigned char *unknown2) __attribute__ ((regparm(3)));
 
t_sendControlPacket _sendControlPacket = (t_sendControlPacket)0x3c3a3da3;;
 
 
typedef unsigned int (*t_sendCommandToDevice)(struct am_recovery_device *rdev,
 
CFStringRef cmd) __attribute__ ((regparm(2)));
 
t_sendCommandToDevice _sendCommandToDevice = (t_sendCommandToDevice)0x3c3a3e3b;
 
 
typedef unsigned int (*t_AMRUSBInterfaceReadPipe)(unsigned int readwrite_pipe, unsigned
 
int read_pipe, unsigned char *data, unsigned int *len);
 
t_AMRUSBInterfaceReadPipe _AMRUSBInterfaceReadPipe = (t_AMRUSBInterfaceReadPipe)0x3c3a27e8;
 
 
typedef unsigned int (*t_AMRUSBInterfaceWritePipe)(unsigned int readwrite_pipe, unsigned
 
int write_pipe, void *data, unsigned int len);
 
t_AMRUSBInterfaceWritePipe _AMRUSBInterfaceWritePipe = (t_AMRUSBInterfaceWritePipe)0x3c3a27cb;
 
*/
 
 
int performOperation(am_restore_device *rdev, CFMutableDictionaryRef message);
 
int socketForPort(am_restore_device *rdev, unsigned int portnum);
 
int sendCommandToDevice(am_recovery_device *rdev, CFStringRef cfs, int block);
 
int sendFileToDevice(am_recovery_device *rdev, CFStringRef filename);
 
 
 
#ifdef __cplusplus
 
}
 
#endif
 
 
#endif
 
 
/* -*- mode:c; indent-tabs-mode:nil; c-basic-offset:2; tab-width:2; */
 
</pre>
 
 
===AFC Connection===
 
...
 
 
===Locking the Device for Sync===
 
When iTunes sends a new song to the device, the device shows a "Sync in progress" screen and when complete, the Music app on the device re-reads the iTunesDB file so it picks up the new song.
 
 
To get this behaviour, first start the notification service:
 
<pre>SOCKET socket;
 
AMDeviceStartService(dev, CFSTR("com.apple.mobile.notification_proxy"), &socket, NULL);</pre>
 
 
Now we post a notificaton message to signal that we are going to start a sync:
 
<pre>AMDPostNotification(socket, CFSTR("com.apple.itunes-mobdev.syncWillStart"), NULL);</pre>
 
 
Next we open the itunes lock file:
 
<pre>afc_file_ref lockref;
 
AFCFileRefOpen(conn, "/com.apple.itunes.lock_sync", 2, &lockref);</pre>
 
 
Now post a notification to say we are going to lock this file, and try and lock it.
 
If the AFCFileRefLock call fails, pause and repeat.
 
<pre>AMDPostNotification(socket, CFSTR("com.apple.itunes-mobdev.syncLockRequest"), NULL);
 
mach_error_t error = AFCFileRefLock(conn, lockref);</pre>
 
 
When the file is successfully locked, post another notification, and stop the notification service.
 
<pre>AMDPostNotification(socket,CFSTR("com.apple.itunes-mobdev.syncDidStart"), NULL);
 
AMDShutdownNotificationProxy(socket);</pre>
 
 
Now the sync can proceed, so copy your files across and make the changes to the iTunesDB.
 
 
To release the lock, start the notification system again, unlock and close the lock file, and send a sync finished notification message:
 
 
<pre>AFCFileRefUnlock(conn, lockref);
 
AFCFileRefClose(conn, lockref);
 
AMDeviceStartService(dev, CFSTR("com.apple.mobile.notification_proxy"), &socket, NULL);
 
AMDPostNotification(socket, &CFSTR("com.apple.itunes-mobdev.syncDidFinish"), NULL);
 
AMDShutdownNotificationProxy(socket);</pre>
 
 
NOTE: You may find that starting the notification_proxy service once and once only at the start of your app and using the same socket in calls to AMDPostNotification works better. iTunes opens and closes the notification_proxy regularly, but it appears to be a bit flakey when you open/close it all the time.
 
 
===Private Functions===
 
 
====How to find address of privates functions in iTunesMobileDevice.dll or MobileDevice.framework ?====
 
...
 
 
 
===Libraries Implementations===
 
 
* [http://code.google.com/p/iphuc/ iPhuc (Command line utility)]
 
* [http://code.google.com/p/iphucwin32/ iPhuc Win32 (Command line utility)]
 
* [http://code.google.com/p/manzana/ manzana (.Net Library)]
 
* [http://code.google.com/p/independence/source/browse/trunk/libPhoneInteraction/ libPhoneInteraction (C Library)]
 

Latest revision as of 13:18, 24 January 2020

MobileDevice Library is used by iTunes to transfer data between iPhone and computer over both USB and WiFi connections.

Windows: iTunesMobileDevice.dll

  • Location: C:\Program Files\Common Files\Apple\Mobile Device Support\iTunesMobileDevice.dll (Program Files (x86) on 64-bit)
  • Supporting CoreFoundation.dll (used for CFStringRef, CFPropertyListRef management) is located in the same dir (when using iTunes prior 9.0).
  • For iTunes 9.0, the location of CoreFoundation.dll is stored in InstallDir registry value under HKLM\SOFTWARE\Apple Inc.\Apple Application Support registry key.

Mac OS X: MobileDevice.framework

  • Location: /System/Library/PrivateFrameworks/MobileDevice.framework
  • Export command: nm /System/Library/PrivateFrameworks/MobileDevice.framework/Versions/A/MobileDevice

Library Interfaces

  • libimobiledevice (provides the same functionality on GNU/Linux)
  • mobiledevice (command line utility for interacting with MobileDevice Framework)
  • SDMMobileDevice (OS X framework written in C that can be used interchangeably with Apple's private framework MobileDevice.framework)
  • MobileDeviceAccess (similar to above, but written in Objective-C)
  • MobileDevice.h (old reverse engineered header for interfacing with MobileDevice library)


Private Functions

Obtaining address

In order to obtain the address of a usable private function in MobileDevice, you will have to be able to understand x86-64 assembly to reverse engineer it. These methods differ slightly based on platform due to how dynamically linked libraries handle position independent code.

Mac OS X (MobileDevice.framework)

A private function is not marked as exported in the mach-o symbol table. This means it cannot be called by simply linking against the library. To call unexported functions, the mach-o symbol table must be stepped through manually to find the offset of a particular function call. Calls can be verified by checking against the offset of the name inside the name table.

Windows (MobileDevice.dll)

Unlike OS X's dynamically linkable libraries, Windows dynamic libraries do not support position independent code in the same manner. A private function will not have its name in the exported symbol table, so in a debugger, like GDB, it will show up as part of another function. However, you will know that it is a separate function as a new stack frame is set up.


Known Error Codes

  • kAMDSuccess = 0x0
  • kAMDUndefinedError = 0xe8000001
  • kAMDBadHeaderError = 0xe8000002
  • kAMDNoResourcesError = 0xe8000003
  • kAMDReadError = 0xe8000004
  • kAMDWriteError = 0xe8000005
  • kAMDUnknownPacketError = 0xe8000006
  • kAMDInvalidArgumentError = 0xe8000007
  • kAMDNotFoundError = 0xe8000008
  • kAMDIsDirectoryError = 0xe8000009
  • kAMDPermissionError = 0xe800000a
  • kAMDNotConnectedError = 0xe800000b
  • kAMDTimeOutError = 0xe800000c
  • kAMDOverrunError = 0xe800000d
  • kAMDEOFError = 0xe800000e
  • kAMDUnsupportedError = 0xe800000f
  • kAMDFileExistsError = 0xe8000010
  • kAMDBusyError = 0xe8000011
  • kAMDCryptoError = 0xe8000012
  • kAMDInvalidResponseError = 0xe8000013
  • kAMDMissingKeyError = 0xe8000014
  • kAMDMissingValueError = 0xe8000015
  • kAMDGetProhibitedError = 0xe8000016
  • kAMDSetProhibitedError = 0xe8000017
  • kAMDRemoveProhibitedError = 0xe8000018
  • kAMDImmutableValueError = 0xe8000019
  • kAMDPasswordProtectedError = 0xe800001a
  • kAMDMissingHostIDError = 0xe800001b
  • kAMDInvalidHostIDError = 0xe800001c
  • kAMDSessionActiveError = 0xe800001d
  • kAMDSessionInactiveError = 0xe800001e
  • kAMDMissingSessionIDError = 0xe800001f
  • kAMDInvalidSessionIDError = 0xe8000020
  • kAMDMissingServiceError = 0xe8000021
  • kAMDInvalidServiceError = 0xe8000022
  • kAMDInvalidCheckinError = 0xe8000023
  • kAMDCheckinTimeoutError = 0xe8000024
  • kAMDMissingPairRecordError = 0xe8000025
  • kAMDInvalidActivationRecordError = 0xe8000026
  • kAMDMissingActivationRecordError = 0xe8000027
  • kAMDWrongDroidError = 0xe8000028
  • kAMDSUVerificationError = 0xe8000029
  • kAMDSUPatchError = 0xe800002a
  • kAMDSUFirmwareError = 0xe800002b
  • kAMDProvisioningProfileNotValid = 0xe800002c
  • kAMDSendMessageError = 0xe800002d
  • kAMDReceiveMessageError = 0xe800002e
  • kAMDMissingOptionsError = 0xe800002f
  • kAMDMissingImageTypeError = 0xe8000030
  • kAMDDigestFailedError = 0xe8000031
  • kAMDStartServiceError = 0xe8000032
  • kAMDInvalidDiskImageError = 0xe8000033
  • kAMDMissingDigestError = 0xe8000034
  • kAMDMuxError = 0xe8000035
  • kAMDApplicationAlreadyInstalledError = 0xe8000036
  • kAMDApplicationMoveFailedError = 0xe8000037
  • kAMDApplicationSINFCaptureFailedError = 0xe8000038
  • kAMDApplicationSandboxFailedError = 0xe8000039
  • kAMDApplicationVerificationFailedError = 0xe800003a
  • kAMDArchiveDestructionFailedError = 0xe800003b
  • kAMDBundleVerificationFailedError = 0xe800003c
  • kAMDCarrierBundleCopyFailedError = 0xe800003d
  • kAMDCarrierBundleDirectoryCreationFailedError = 0xe800003e
  • kAMDCarrierBundleMissingSupportedSIMsError = 0xe800003f
  • kAMDCommCenterNotificationFailedError = 0xe8000040
  • kAMDContainerCreationFailedError = 0xe8000041
  • kAMDContainerP0wnFailedError = 0xe8000042
  • kAMDContainerRemovalFailedError = 0xe8000043
  • kAMDEmbeddedProfileInstallFailedError = 0xe8000044
  • kAMDErrorError = 0xe8000045
  • kAMDExecutableTwiddleFailedError = 0xe8000046
  • kAMDExistenceCheckFailedError = 0xe8000047
  • kAMDInstallMapUpdateFailedError = 0xe8000048
  • kAMDManifestCaptureFailedError = 0xe8000049
  • kAMDMapGenerationFailedError = 0xe800004a
  • kAMDMissingBundleExecutableError = 0xe800004b
  • kAMDMissingBundleIdentifierError = 0xe800004c
  • kAMDMissingBundlePathError = 0xe800004d
  • kAMDMissingContainerError = 0xe800004e
  • kAMDNotificationFailedError = 0xe800004f
  • kAMDPackageExtractionFailedError = 0xe8000050
  • kAMDPackageInspectionFailedError = 0xe8000051
  • kAMDPackageMoveFailedError = 0xe8000052
  • kAMDPathConversionFailedError = 0xe8000053
  • kAMDRestoreContainerFailedError = 0xe8000054
  • kAMDSeatbeltProfileRemovalFailedError = 0xe8000055
  • kAMDStageCreationFailedError = 0xe8000056
  • kAMDSymlinkFailedError = 0xe8000057
  • kAMDiTunesArtworkCaptureFailedError = 0xe8000058
  • kAMDiTunesMetadataCaptureFailedError = 0xe8000059
  • kAMDAlreadyArchivedError = 0xe800005a
  • kAMDProhibitedBySupervision = 0xe8000083

For the latest error codes you can look at the pseudo-code of AMDErrorString