AppController.h
/* * AppController.h * MachOView * * Created by psaghelyi on 15/06/2010. * */#import <Cocoa/Cocoa.h>@class MVPreferenceController;@interface MVAppController : NSObject <NSApplicationDelegate,NSOpenSavePanelDelegate>{ MVPreferenceController * preferenceController;}//偏好设置- (IBAction)showPreferencePanel:(id)sender;//附加- (IBAction)attach:(id)sender;@end
appcontroller.mm
/* * APPCONTROLLER.MM * machoview * * Created by Psaghelyi on 15/06/2010. * */#import "Common.h" #import "AppController.h" #import "DataController.h" #import "Document.h" #import " PreferenceController.h "#import" Attach.h "//counters for statisticsint64_t nrow_total; Number of rows (loaded and empty) int64_t nrow_loaded; Number of Loaded rows//============================================================================@ Implementation mvappcontroller//-----------------------------------------------------------------------------( BOOL) Applicationshouldopenuntitledfile: (NSApplication *) sender{return NO; -----------------------------------------------------------------------------(BOOL) applicationshouldterminateafterlastwindowclosed: (nsapplication *) sender{return NO;} ----------------------------------------------------------------------------//new Way did not write-(ibaction) newdocument :(ID) sender{NSLog (@ "not yet possible");} //----------------------------------------------------------------------------//Whether it is running-(BOOL) isonlyrunningmachoview{//Get information about the process nsprocessinfo * ProcInfo = [Nsprocessinfo process Info]; Get the program package (app package is a mainbundle) nsbundle * mainbundle = [NSBundle mainbundle]; Gets the cfbundleshortversionstring of the current process//Returns a list of property information in the receiver associated with the specified key NSString * versionstring = [Mainbundle objectforinfodiction arykey:@ "Cfbundleshortversionstring"]; Nsuinteger numberofinstance = 0; Return a workspace//provide service//1) open, manipulate files/devices, get File/device information//2) tracking files, device and database changes//3) set or get Finder information for files//4) operation Application Nsworkspa CE * workspace = [Nsworkspace SharedWorkspace]; Gets the currently running apps for (Nsrunningapplication * runningapplication in [workspace runningapplications]) {//check if the process name matches/ /executableurl gets the executable URL of the bundle class instance//lastpathcomponent gets the last file name in the path nsstring * filename = [[runningapplication exec Utableurl] lastpathcomponent]; Determine if the name is equal if ([FileName isequaltostring: [ProcInfo processName]] = = NO) {continue; }//Check if version string matches//get Bundl by URLE NSBundle * bundle = [NSBundle bundlewithurl:[runningapplication Bundleurl]]; Determines if equal to the current process if ([versionstring isequaltostring:[bundle objectforinfodictionarykey:@ "Cfbundleshortversionstring" ]] = = YES && ++numberofinstance > 1) {return NO; }} return YES; ----------------------------------------------------------------------------//Attach mode to open simultaneous parsing mach-o header-( ibaction) Attach: (ID) sender{//alert nsalert *alert = [Nsalert alertwithmessagetext:@ "Insert PID to attach to:" defaultbutton:@ "Attach" alternatebutton:@ "Cancel" Otherbutton:nil informativetextwithformat:@ ""]; Initializes a text box Nstextfield *input = [[Nstextfield alloc] Initwithframe:nsmakerect (0, 0, 200, 24)]; Set the default string [input setstringvalue:@ "]; Set the frame view as input [alert setaccessoryview:input]; Returns the button value Nsinteger buttons = [Alert RunModal]; if (Button = = NSALertdefaultreturn) {//Set to non-editable [input validateediting]; Get pid pid_t targetpid = [input intvalue]; NSLog (@ "Attach to process%d", targetpid); Entry address mach_vm_address_t mainaddress = 0; Find the entry address if (Find_main_binary (Targetpid, &mainaddress)) {NSLog (@ "Failed to find main binary address!"); Return } uint64_t aslr_slide = 0; uint64_t imagesize = 0; Gets the mirror size if ((ImageSize = Get_image_size (mainaddress, Targetpid, &aslr_slide)) = = 0) {NSLog (@ "[ERROR] Go t image file size equal to 0! "); Return The buffer size (file) required to allocate macho uint8_t *readbuffer = (uint8_t*) malloc (imagesize); if (Readbuffer = = NULL) {NSLog (@ "Can ' t allocate mem for dumping target!"); Return }//Last read these sections and dump their contents into the buffer if (dump_binary (mainaddress, Targetpid, Readbuffer, aslr_slide)) {NSLog (@ "Main b Inary memory Dump failed! "); Free (readbuffer); Return }//dumps buffer contents to temporary file to use Nsdocument modEl//Splicing temporary file name + process name such as: "/var/folders/l8/3kn0r51s3qdbbnxb9ng2gvb40000gn/t/machoview_2.4.xxxxxxxxxxx" const char *tmp = [[Mvdocument temporarydirectory] utf8string]; The buffer for the absolute path name of the temporary file that holds the number of data char *dumpfilepath = (char*) malloc (strlen (TMP) +1); if (DumpFilePath = = NULL) {NSLog (@ "Can ' t allocate mem for temp filename path!"); Free (readbuffer); Return }//Copy strcpy (DumpFilePath, TMP); int outputFile = 0; Create a file in the system with a unique filename and open the IF ((OutputFile = Mkstemp (dumpfilepath)) = =-1) {NSLog (@ "Mkstemp failed!"); Free (DumpFilePath); Free (readbuffer); Return }//write if (write (OutputFile, readbuffer, imagesize) = =-1) {NSLog (@ "[ERROR]" write error at%s occurred!\n ", DumpFilePath); Free (DumpFilePath); Free (readbuffer); Return } NSLog (@ "\n[ok] full binary dumped to%s!\n\n", DumpFilePath); Close (OutputFile); Open file [self Application:nsapp openfile:[nsstring Stringwithcstring:dumpfIlepath Encoding:nsutf8stringencoding]]; Delete temporary dump file Nsfilemanager * FileManager = [Nsfilemanager Defaultmanager]; [FileManager removeitematpath:[nsstring Stringwithcstring:dumpfilepath encoding:nsutf8stringencoding] Error:NULL]; Free (DumpFilePath); Free (readbuffer); } else if (Button = = Nsalertalternatereturn) {//} else {NSAssert1 (NO, @ "Invalid Input Dialog button%ld", but ton); }}//----------------------------------------------------------------------------//open Mode open-(ibaction) OpenDocument: (ID) sender{//Open File View Nsopenpanel *openpanel = [Nsopenpanel Openpanel]; Whether to display the directory of panel encapsulated files [Openpanel Settreatsfilepackagesasdirectories:yes]; Set to multi-select mode [Openpanel Setallowsmultipleselection:yes]; Non-selectable folder [Openpanel Setcanchoosedirectories:no]; Settings can be selected file [Openpanel Setcanchoosefiles:yes]; Set the agent to call Shouldshowfilename for itself to filter the files in the open panel [Openpanel setdelegate:self]; Alarm style window//completionhandler parameter for event response [Openpanel Beginsheetmodalforwindow:nil Completionhandler:^ (Nsinteger result) {//Judging click OK if (result! = Nsokbutton) {return; }//Before closing the panel, an error//removal window may appear [Openpanel orderout:self]; Traverse the selected file path for (Nsurl * URL in [openpanel URLs]) {//All open (via multi-document mode) [Self Application:nsapp openFile : [URL path]]; } }];} ----------------------------------------------------------------------------//Protocol-----Filtering file-(BOOL) panel: (ID) Sender Shouldshowfilename: (nsstring*) filename{//File URL nsurl * url = [Nsurl fileurlwithpath:filename]; Determine if the folder NSNumber * isdirectory = nil; [url getresourcevalue:&isdirectory forkey:nsurlisdirectorykey error:null]; if ([isdirectory boolvalue] = = yes) {return yes; }//Skipping the symbolic link, etc.//judging if there are some symbolic links nsnumber * Isregularfile = nil; [url getresourcevalue:&isregularfile forkey:nsurlisregularfilekey error:null]; if ([isregularfile boolvalue] = = no) {return no; }//Check file for Magic//File handle Nsfilehandle * FileHandle = [NSFILehandle Filehandleforreadingatpath:filename]; NSLog (@ "Filehandleforreadingatpath-----%@!\n\n", filename); Reads the specified number of characters NSData * magicdata = [FileHandle readdataoflength:8]; NSLog (@ "magicdata-----%@!\n\n", magicdata); Close handle [FileHandle closefile]; Determine length if ([Magicdata length] < sizeof (uint32_t)) {return NO; }//Compare uint32_t Magic = * (uint32_t*) [magicdata bytes]; NSLog (@ "Magic-----%8x!\n\n", magic); if (Magic = = Mh_magic | | magic = = MH_MAGIC_64 | | Magic = = Fat_cigam | | Magic = = fat_magic) {return YES; } if ([Magicdata length] < sizeof (uint64_t)) {return NO; } if (* (uint64_t*) [magicdata bytes] = = * (uint64_t*) "!<arch>\n") {return YES; } return NO; ----------------------------------------------------------------------------//program will start-(void) Applicationwillfinishlaunching: (nsnotification *) anotification{BOOL isfirstmachoview = [Self Isonlyrunningmachoview ]; Disable state recovery, which is not very useful for machoview if ([[Nsuserdefaults StandardUserdefaults] Objectforkey: @ "applepersistenceignorestate"] = = nil) [[Nsuserdefaults Standarduserdefaults] Setbool:y ES forkey:@ "Applepersistenceignorestate"]; Load user ' s defaults for preferences//if ([[[Nsuserdefaults Standarduserdefaults] Objectforkey: @ "Usellvmdisassembler "] = nil)//Qflag = [[Nsuserdefaults standarduserdefaults] boolforkey:@" Usellvmdisassembler "]; Get a File Manager Nsfilemanager * FileManager = [Nsfilemanager Defaultmanager]; NSString * TempDir = [mvdocument temporarydirectory]; __autoreleasing Nserror * ERROR; Delete previously forgotten temporary files if (Isfirstmachoview && [FileManager fileexistsatpath:tempdir isdirectory:null] = = YES) {// Remove if ([FileManager removeitematpath:tempdir error:&error] = = NO) {[Nsapp presenterror:error]; }}//creates a placeholder for temporary files//Returns a Boolean value indicating whether a file or directory exists in the specified path if ([FileManager fileexistsatpath:tempdir isdirectory:null] = = NO) {//create a specified directory path with the given property if ([FileManager Createdirectoryatpath:tempdirWithintermediatedirectories:no Attributes:nil error:&am P;error] = = NO) {//Invoke error dialog box [Nsapp Presenterror:error]; }}}//----------------------------------------------------------------------------//program started-(void) Applicationdidfinishlaunching: (nsnotification *) anotification {#ifdef Mv_statistics nrow_total = nrow_loaded = 0; The thread begins printing (for debugging neglect) [Nsthread detachnewthreadselector: @selector (printstat) totarget:self Withobject:nil]; #endif// The default opens the file dialog box if ([[Nsuserdefaults standarduserdefaults] objectforkey:@ "Openatlaunch"]! = nil) {if ([[Nsuserdefaults Standarduserdefaults] boolforkey:@ "openatlaunch"] = = YES) {if ([[[Nsdocumentcontroller Shareddocumentcontroller] Documents] count] = = 0) {[Self opendocument:nil]; }}}}//----------------------------------------------------------------------------//program will end-(void) Applicationwillterminate: (nsnotification *) anotification{ BOOL Islastmachoview = [self isonlyrunningmachoview]; if (Islastmachoview = = YES) {//delete temporary file Nsfilemanager * FileManager = [Nsfilemanager Defaultmanager]; Returns the temporary directory of the current user NSString * tempdir = [mvdocument temporarydirectory]; NSLog (@ "Can ' t allocate mem for temp filename path!%@", tempdir); Delete [FileManager removeitematpath:tempdir error:null]; }}//----------------------------------------------------------------------------//callback function Open File-(BOOL) Application: ( NSApplication *) theapplication openFile: (NSString *) filename{NSLog (@ "Open file:%@", filename); __autoreleasing Nserror *error; Get a multi-document controller Nsdocumentcontroller * Documentcontroller = [Nsdocumentcontroller Shareddocumentcontroller]; Nsdocumentcontroller Create manage multiple mvdocument//mvdocument create manage multiple Nswindowcontroller//nswindowcontroller//Create a document from a file path At the same time display (through the proxy implementation details)//mvdocument must implement the function has://Window name//-(NSString *) windownibname; Specifies the window controller//-(void) windowcontrollerdidloadnib: (NSWINdowcontroller *) Acontroller; You must implement document data that creates and returns supported types, typically files that write data to a NSData object. -(NSData *) Datarepresentationoftype: (NSString *) Atype; You must implement an internal data structure that transforms a NSData object (containing a particular type of document data) into a document so that the document is ready to display its contents. NSData objects are typically generated from documents that read document files. -(BOOL) Loaddatarepresentation: (NSData *) Data: (NSString *) Atype; Mvdocument * document = [Documentcontroller opendocumentwithcontentsofurl:[nsurl fileurlwithpath:filename] Display:yes error:&error]; Determines if the document can be opened if (!document) {[Nsapp presenterror:error]; return NO; } return YES; ----------------------------------------------------------------------------//Thread callback-(void) printstat{for (;;) {NSLog (@ "stat:%lld/%lld rows in memory\n", nrow_loaded,nrow_total); [Nsthread sleepfortimeinterval:1]; }}//----------------------------------------------------------------------------//System Preferences (display a nib)-(ibaction) ShowPreferencepanel: (ID) sender{if (!preferencecontroller) {preferencecontroller = [[Mvpreferencecontroller allo c] init]; } [Preferencecontroller showwindow:self];} @end
Machoview source code (APPCONTROLLER.MM)