Programmatically lock the screen

Posted: June 5th, 2016 | Author: | Filed under: macOS, Programming | Tags: , , , | No Comments »

The Keychain Access application has a preference to display a “Lock Screen” menu item in the menubar:


Keychain Access Preferences

After enabling the checkbox ‘Show keychain status in menu bar’, this menu will appear in the menubar:


Lock Screen in Menubar

This menu is located here:

/Applications/Utilities/Keychain Access.app/Contents/Resources/Keychain.menu

and it is fairly easy to find the method
-[AppleKeychainExtra _lockScreenMenuHit:].


-[AppleKeychainExtra _lockScreenMenuHit:]

That’s this simple! The method -[AppleKeychainExtra _lockScreenMenuHit:] simply calls the private method ‘SACLockScreenImmediate’ from the Login private framework. The Login framework takes care of all the hard work.

Now we can create a simple application to lock the screen. Here is the whole source code:

extern void SACLockScreenImmediate();

int main()
{
    SACLockScreenImmediate();
    return 0;
}

To compile it:

clang -F /System/Library/PrivateFrameworks -framework login -o LockScreen LockScreen.c

You can download the precompiled binary here: LockScreen.zip


Disable swipe to delete in Mail.app on OS X 10.11

Posted: May 10th, 2016 | Author: | Filed under: code injection, macOS, Mail | 18 Comments »

OS X 10.11 ‘El Capitan’ added a new feature to Mail.app ‘Swipe to manage your inbox’:

Swipe to manage your inbox.
Now you can take care of your email with a swipe, just like on your iOS devices. Need to triage your inbox? Swipe right to mark an email as read or unread, or swipe left to delete. You’ll be focused on what’s important in no time.


Swipe To Delete

 

I find this new feature extremely annoying as I keep triggering it by accident. Sadly it seems that there is no preference (even secret preference) to disable this feature. But the good news is that Mail.app supports plugins.

To disable this feature, I created a simple Mail.app plugin. A precompiled version for Mail 9.3 (3124)
(OS X 10.11.4) can be downloaded here: DisableSwipeGesture.mailbundle.zip

 

You can download the source code here : Download ‘DisableSwipeGesture’ Source Code

 

Installation using the precompiled version for Mail 9.3 (3124) – OS X 10.11.4:

  • Download the precompiled version
  • Unzip
  • Copy the file into ~/Library/Mail/Bundles/
  • Relaunch Mail.app

 

Installation for other versions of Mail.app:

  • Download the DisableSwipeGesture source code
  • Open the project in Xcode
  • Build
  • Relaunch Mail.app

 

How does it work?

Mail.app uses a standard NSTableView to support the swipe to delete gesture. It implements the AppKit -tableView:rowActionsForRow:edge: delegate method to add the swipe to delete feature.

Before handling a swipe event, AppKit checks if swipe to delete is supported with the internal method -(BOOL)[NSTableView _allowSwipeToDeleteForEvent:]. The default implementation checks if the NSTableView is a view based tableview and if there is a delegate. The ‘DisableSwipeGesture’ Mail plugin overrides this internal method to always return NO i.e. to never allow swipe to delete. Note that this plugin only changes the behavior of Mail.app, it does not affect any other app. However the same mechanism could be used to disable the swipe to delete feature for any OS X app supporting plugins.

 

Mail.app plugin compatibility

Before loading any plugin, Mail.app checks if the plugin’s Info.plist contains the current Mail.app ‘PluginCompatibilityUUID’ value. If this is not the case, Mail.app will refuse to load the plugin and you will see an alert:


Incompatible Plugin

If you use this ‘DisableSwipeGesture’ plugin and you update Mail.app though an OS X update, you will need to update the PluginCompatibilityUUID value in the Info.plist of the ‘DisableSwipeGesture’ plugin. The simplest solution is to recompile the plugin using the steps provided in ‘Installation for other versions of Mail.app’. The Xcode project has a build phase that will extract the PluginCompatibilityUUID from /Application/Mail.app and copy it into the Info.plist.


QuickLook plugin to preview .strings files

Posted: March 25th, 2014 | Author: | Filed under: Debugging, macOS, Programming | Tags: | 2 Comments »

OS X and iOS use .strings files for localized text strings as described in the String Resources Documentation:

Resource files that contain localizable strings are referred to as strings files because of their filename extension, which is .strings.

It is yet annoying that OS X and Xcode don’t provide a built-in QuickLook plugin for previewing .strings files. When you preview such a file in QuickLook you see this window:


Without 'StringsFile' QuickLook plugin

To solve this issue, here is a simple QuickLook plugin called ‘StringsFile’ that lets you preview .strings files (plain text .strings and binary property plist .strings).
This QuickLook plugin is really useful to quickly check the content of a .strings file. When you preview such a file, you will now see:


With 'StringsFile' QuickLook plugin

A precompiled version can be downloaded here: StringsFile.qlgenerator.zip

You can download the source code here : Download ‘StringsFile’ Source Code

Installation:

  • Download the precompiled version
  • Unzip
  • Copy the file into /Library/QuickLook/ or ~/Library/QuickLook/
  • Execute the command “qlmanage -r” in the Terminal – or restart the machine

Update (02.04.2014): The plugin has been updated to also generate a thumbnail for .strings files.


Thumbnail


Using AddressSanitizer with Xcode 4.6.1

Posted: April 10th, 2013 | Author: | Filed under: Debugging, macOS, Programming | Tags: , , , , , | 3 Comments »

Clang 3.3 now supports AddressSanitizer. Here is the description from the Clang 3.3 documentation:

AddressSanitizer is a fast memory error detector. It consists of a compiler instrumentation module and a run-time library. The tool can detect the following types of bugs:

  • Out-of-bounds accesses to heap, stack and globals
  • Use-after-free
  • Use-after-return (to some extent)
  • Double-free, invalid free

Typical slowdown introduced by AddressSanitizer is 2x.

Using AddressSanitizer by manually compiling a file is well documented. On the other hand using Xcode 4.6.1 to build a complex project with AddressSanitizer enabled is not so easy. Following are the steps to build an Xcode project with AddressSanitizer.

Note that I used Xcode 4.6.1 when writing this article. Xcode 4.6.1 contains a Clang build based on LLVM 3.2. Most likely a future Xcode build will contain a Clang build based on LLVM 3.3 which would simplify the use of AddressSanitizer in Xcode.

1- Building Clang 3.3

Since Xcode 4.6.1 contains an old build of Clang, we need to get and build Clang trunk. This is fairly easy. Here is what I did:

– svn co http://llvm.org/svn/llvm-project/llvm/trunk llvm
– cd llvm/tools
– svn co http://llvm.org/svn/llvm-project/cfe/trunk clang
– cd ../..
– cd llvm/projects
– svn co http://llvm.org/svn/llvm-project/compiler-rt/trunk compiler-rt
– cd ../..
– mkdir build
– cd build
– ../llvm/configure –enable-optimizations
– make -j `sysctl -n hw.logicalcpu`

2- Tell Xcode 4.6.1 to use Clang 3.3 we just compiled

The simplest solution I found is to add the following user define in the Xcode target:
CC = “PATH_TO/llvm/build/Debug+Asserts/bin/clang”;
You need to set PATH_TO to the folder where you compiled llvm.

3- Make sure the deployment target is set to 10.7 or higher.

I used the deployment target set to 10.7.

4- Add the C flag and linker flag -fsanitize=address

Add the C flag -fsanitize=address
Add the linker flag -fsanitize=address

5- Compile your project

Congratulations! You now have a build of your project with AddressSanitizer enabled.

6- Running the application

Xcode 4.6.1 fails to run this executable but you can run it from the Terminal and AddressSanitizer will detect possible memory errors.
If your application has a memory error, you will see an error message like:


Memory Error with AddressSanitizer

7- Symbolize the symbols

Currently AddressSanitizer does not symbolize its output.
You will need to manually symbolize the addresses. This can easily be done with atos (see man atos) and the dSYM file produced during the compilation (you might need to turn on “DWARF with dSYM File” in the Xcode target).

For example to symbolize the symbol 0x100001d86 in the AddressSanitizer message:

Alex:MyApplication alex$ atos -o build/Debug/MyApplication.app.dSYM/Contents/Resources/DWARF/MyApplication 0x100001d86
-[AppDelegate applicationDidFinishLaunching:] (in MyApplication) (AppDelegate.mm:23)

Useful references

Clang 3.3 documentation for AddressSanitizer: http://clang.llvm.org/docs/AddressSanitizer.html

AddressSanitizer HomePage: http://code.google.com/p/address-sanitizer/


Simple code injection using DYLD_INSERT_LIBRARIES

Posted: December 18th, 2012 | Author: | Filed under: code injection, Debugging, DYLD_INSERT_LIBRARIES, macOS, Programming | 15 Comments »

In the following article I will describe a simple method to inject code into executables on Mac OS X 10.8 using the DYLD_INSERT_LIBRARIES environment variable.
I also wrote a simple launcher that starts Calculator.app and injects code to modify the About Box of Calculator.app. When bringing the About Box window of Calculator.app, a custom alert will be displayed:

Modifying Calculator.app AboutBox to display a custom alert

Note: Code injection should be used with care. You should probably not ship applications using code injection and the discussed environment variable DYLD_INSERT_LIBRARIES.

On Mac OS X 10.8, there are several ways to inject code into an arbitrary 64-bit process:

  • writing a plugin if the targeted application supports plugins. Such a solution is possible for applications like Safari, Mail, Xcode… but not for the Calculator.app.
  • Injecting code through Scripting Additions: you create a daemon to watch the launch of the targeted application and this daemon sends a custom Apple event to trigger the code injection. This solution is apparently used by 1Password 3.
  • you can inject code using Mach ports by using mach_override and mach_inject but it has some downsides (you need to be in the procmod group or root).
  • Injecting code through a kernel extension: This is really powerful but the code runs in the kernel.
  • Modifying the binary of the application but this can’t be reused and you need to reapply the changes for each new version of the application.
  • Injecting code using the DYLD_INSERT_LIBRARIES environment variable: this is a really simple solution to implement but you can only inject code in the application you launch.

Now that we know the different ways for injecting code, let’s look more in details at the DYLD_INSERT_LIBRARIES environment variable.

Using DYLD_INSERT_LIBRARIES has several advantages:

  • It is simple to implement.
  • All the code runs in userland and you don’t need to be root or run with the procmod group.
  • You don’t rely on complex third party code.
  • It can be used to inject code in any application you start.
  • You only inject code in a specific application.

It has some downsides:

  • You can only inject code in the applications you start.

On Mac OS X, the dynamic linker (dyld) can be used to load a dynamic library specified in the DYLD_INSERT_LIBRARIES environment variable into an executable. I created a simple dynamic library that replaces the -[CalculatorController showAbout:] method of Calculator.app with a custom implementation. Following is the code of the dynamic library (ACCalculatorOverrides.m). Here is what it does:

  • I created an object called ACCalculatorOverrides with a +(void)load class method. This code is invoked really early by the runtime. It exchanges the implementation of the method -[CalculatorController showAbout:] by the implementation of -[ACCalculatorOverrides patchedShowAbout:].
  • The method -[ACCalculatorOverrides patchedShowAbout:] will call the original method to display the original About Box and then display a custom alert.

#import "ACCalculatorOverrides.h"

#include <stdio.h>
#include <objc/runtime.h>
#include <Foundation/Foundation.h>
#include <AppKit/AppKit.h>

static IMP sOriginalImp = NULL;

@implementation ACCalculatorOverrides

+(void)load
{
	// We replace the method -[CalculatorController showAbout:] with the method -[ACCalculatorOverrides patchedShowAbout:]
	Class originalClass = NSClassFromString(@"CalculatorController");
	Method originalMeth = class_getInstanceMethod(originalClass, @selector(showAbout:));
	sOriginalImp = method_getImplementation(originalMeth);
	
	Method replacementMeth = class_getInstanceMethod(NSClassFromString(@"ACCalculatorOverrides"), @selector(patchedShowAbout:));
	method_exchangeImplementations(originalMeth, replacementMeth);
}

-(void)patchedShowAbout:(id)sender
{
	// We first call the original method to display the original About Box
	sOriginalImp(self, @selector(showAbout:), self);
	
	// Run our custom code which simply display an alert
	NSAlert *alert = [NSAlert alertWithMessageText:@"Code has been injected!" defaultButton:@"OK" alternateButton:nil otherButton:nil informativeTextWithFormat:@"The code has been injected using DYLD_INSERT_LIBRARIES into Calculator.app"];
	[alert runModal];
}

@end

It is possible to manually build this dynamic library by running in the Terminal:

gcc -framework AppKit -framework Foundation -o CalculatorOverrides.dylib -dynamiclib ACCalculatorOverrides.m

and manually injecting it into Calculator.app by running in the Terminal:

DYLD_INSERT_LIBRARIES=/PATH_TO/CalculatorOverrides.dylib /Applications/Calculator.app/Contents/MacOS/Calculator &

But to make it simpler to use, let’s write a launcher. The launcher will be a background-only application (LSUIElement set to YES) that will execute the previously mentioned command line and then quit itself. Here is the code of the launcher:


#import "AppDelegate.h"

@implementation AppDelegate

- (void)dealloc
{
    [super dealloc];
}

-(void)bringToFrontApplicationWithBundleIdentifier:(NSString*)inBundleIdentifier
{
	// Try to bring the application to front
	NSArray* appsArray = [NSRunningApplication runningApplicationsWithBundleIdentifier:inBundleIdentifier];
	if([appsArray count] > 0)
	{
		[[appsArray objectAtIndex:0] activateWithOptions:NSApplicationActivateIgnoringOtherApps];
	}
	
	// Quit ourself
	[[NSApplication sharedApplication] terminate:self];
}

-(void)launchApplicationWithPath:(NSString*)inPath andBundleIdentifier:(NSString*)inBundleIdentifier
{
	if(inPath != nil)
	{
		// Run Calculator.app and inject our dynamic library
		NSString *dyldLibrary = [[NSBundle bundleForClass:[self class]] pathForResource:@"CalculatorOverrides" ofType:@"dylib"];
		NSString *launcherString = [NSString stringWithFormat:@"DYLD_INSERT_LIBRARIES=\"%@\" \"%@\" &", dyldLibrary, inPath];
		system([launcherString UTF8String]);
		
		// Bring it to front after a delay
		[self performSelector:@selector(bringToFrontApplicationWithBundleIdentifier:) withObject:inBundleIdentifier afterDelay:1.0];
	}
}

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
	NSString *calculatorPath = @"/Applications/Calculator.app/Contents/MacOS/Calculator";
	if([[NSFileManager defaultManager] fileExistsAtPath:calculatorPath])
		[self launchApplicationWithPath:calculatorPath andBundleIdentifier:@"com.apple.calculator"];
}

@end

Download: You can download here the compiled Calculator Launcher. If you launch it, it will launch the Calculator.app and inject the code to display an alert when you display the About Box of Calculator.app. If you are interested by the source code, the full sources are available here.


StuffIt ContextualMenu for MacOSX 10.6

Posted: September 21st, 2010 | Author: | Filed under: macOS, Programming | Tags: , , , , , , , , | 3 Comments »

Smith Micro Software released StuffIt Deluxe® 2011 this week. If you don’t know StuffIt Deluxe®, it is described like this:

The StuffIt Deluxe® package gives you all the features you need to backup, share, archive, encrypt and shrink your photos, music, and other documents without compromising quality. StuffIt’s advanced technology specializes in the compression of MP3, PDF and graphics files with no quality loss. Shrink documents up to 98% of their original size. Use StuffIt to free-up space on your computer and to fit more compressed files onto CD/DVDs or other drives.

With MacOS X 10.5 (and older), it was possible to access some features of StuffIt directly from the Finder using a Contextual Menu. Here is the description in the StuffIt User Guide of The StuffIt Contextual Menu:

StuffItCM is an alternative to MagicMenu. Except for keyboard shortcuts, all the commands available in MagicMenu are also available in the StuffIt Contextual Menu. Rather than appearing in the Finder menubar, the Contextual Menu appears when you hold down the Control (Ctrl) key or right-click while selecting a file in the Finder.

Mac OS 10.4 (Tiger) users will find the “StuffIt” option at the top-level of the Finder’s contextual menu.

Mac OS 10.5 (Leopard) users will find non-Apple contextual menus under “More”.

In Mac OS 10.6 (Snow Leopard), Apple has removed support for third party contextual menu plugins. As a result, the StuffIt Contextual Menu is not available.

This is yet partially true. Apple indeed removed the old contextual menu API in MacOSX 10.6. But Apple added a new API. You may have heared about it in my previous post “Implementing a Service on 10.6”.

To reenable this missing feature for 10.6 users, I built a Service that adds 2 menu items in the Contextual Menu of the Finder: ‘UnStuff with StuffIt’ and ‘Stuff with StuffIt’. The ‘UnStuff with StuffIt’ menu item is only visible when you select a file compressed by StuffIt in the Finder. The ‘Stuff with StuffIt’ menu item will appear for any file.

Figure 1: ‘UnStuff with StuffIt’ in the Finder contextual menu


UnStuff with StuffIt

Figure 2: These 2 menu items are also available in the ‘Services’ menu


Stuff with StuffIt

The implementation of this Service is really simple: It uses the 2 command line tools ‘stuff’ and ‘unstuff’ installed by StuffIt Deluxe® 2011 and StuffIt Deluxe® 2010 (I don’t know if previous versions of StuffIt Deluxe® install these 2 command line tools).

Download: You can download here the compiled StuffIt Service. To install it, unzip it, then move the ‘StuffItService.service’ in your ~/Library/Services folder and log out. If you are interested by the source code, the full sources are available here.


Implementing a Service on 10.6

Posted: July 27th, 2010 | Author: | Filed under: macOS, Programming | Tags: , , , , , , | 1 Comment »

In this post I talk on how to write a Service for MacOS X 10.6. If you don’t know what is a Service, Apple describes it here http://www.apple.com/macosx/refinements/:

The Services menu in Mac OS X lets you use features of one application while working in another. In Snow Leopard, services are more simplified, streamlined, and helpful. The Services menu is contextual, so it shows just the services appropriate for the application you’re using or content you’re viewing rather than all available services. You can access services with a right click of your mouse or Control-click of your trackpad. You can configure the menu to show only the services you want, and you can even create your own services using Automator.

The technical documentation from Apple on how to write your own Service is available here: Services Implementation Guide. Writing a Service for MacOS X 10.6 is not complicated in itself. Some useful documentation (on how to correctly write the Info.plist of the service) is available but it is hard to find a working sample. So the aim at this post is to provide a sample Service with the source code. The Service is really simple and can do 2 tasks:

  • implement a functionality similar to the ‘Paste and Match Style’ feature available in most applications under the Edit menu.
  • implement a functionality to copy the selection from the front application as plain text in the Clipboard.

Download: You can download here the compiled Service. To install it, unzip it, then move the ‘Citrouille.service’ in your ~/Library/Services folder and log out. If you are interested by the source code, the full sources are available here.

‘Paste and Match Style’: A simple implementation of the ‘Paste and Match Style’ functionality. When you copy text (with whatever fonts, sizes and colours it had), you can select ‘Paste and Match Style’ from the Services menu in any application to paste the text with the current style. This feature doesn’t have advantages over the built-in ‘Paste and Match Style’ from many MacOSX applications.

Figure 1: ‘Paste and Match Style’ in the Services menu


WithoutTextSelection

The implementation for ‘Paste and Match Style’ is really simple:

- (void)doPasteAsPlainText:(NSPasteboard *)pboard userData:(NSString *)userData error:(NSString **)error
{
	NSString *outString = @"";
	BOOL hasError = NO;
	
	if(!hasError)
	{
		// Test for strings on the pasteboard.
		NSArray *classes = [NSArray arrayWithObject:[NSString class]];
		NSDictionary *options = [NSDictionary dictionary];
		
		if (![[NSPasteboard generalPasteboard] canReadObjectForClasses:classes options:options])
		{
			outString = @"";
			hasError = YES;
			*error = NSLocalizedString(@"Error: There is no string in the pasteboard.", @"outputing nothing");
		}
	}
	
	if(!hasError)
	{
		outString = [[NSPasteboard generalPasteboard] stringForType:NSPasteboardTypeString];
		if(outString == nil)
		{
			outString = @"";
			hasError = YES;
			*error = NSLocalizedString(@"Error: There is no valid string in the pasteboard.", @"outputing nothing");
		}
	}
	
	
	// Write the string onto the pasteboard.
	[pboard clearContents];
	[pboard writeObjects:[NSArray arrayWithObject:outString]];
}
 

‘Copy as Plain Text’: you can select a text in any application and select ‘Copy as Plain Text’ from the Services menu in any application. This will copy the selected text as plain text (no style) in the clipboard.

Figure 2: ‘Copy as Plain Text’ in the Services menu


WithTextSelection

- (void)doCopyAsPlainText:(NSPasteboard *)pboard userData:(NSString *)userData error:(NSString **)error
{
	// Test for strings on the pasteboard.
	NSArray *classes = [NSArray arrayWithObject:[NSString class]];
	NSDictionary *options = [NSDictionary dictionary];
	
	if (![pboard canReadObjectForClasses:classes options:options])
	{
		*error = NSLocalizedString(@"Error: couldn't get text.", @"pboard couldn't give string.");
		return;
	}
	
	NSString *pboardString = [pboard stringForType:NSPasteboardTypeString];
	[[NSPasteboard generalPasteboard] clearContents];
	[[NSPasteboard generalPasteboard]  writeObjects:[NSArray arrayWithObject:pboardString]];
}
 

Cornichon

Posted: March 17th, 2010 | Author: | Filed under: Cornichon, macOS | Tags: , , , , , , , , | No Comments »

Cornichon is a powerful tool you can use to dynamically profile Mac OS X applications on the system and track the process’ performance over time.

Figure 1: Profiling Safari with Cornichon

screenshot-small

The Cornichon application includes the ability to:

  • Profile Mac OS X applications
  • Profile iPhone applications running in the iPhone simulator
  • Examine the behavior of one or more processes
  • See the different collected data of a process in real time in a graph
  • Export the data as TAB files that you can later easily import in Apple Numbers or Microsoft Excel

With the Cornichon application, you can inspect different aspects of a process’ behavior:

  • CPU usage
  • Resident memory size (RSIZE)
  • Resident private address space size (RPRVT)
  • Total memory size (VSIZE)
  • Number of threads

Why using Cornichon?

Apple provides several tools that allow you to profile Mac OS X applications: Activity Monitor, Instruments, and some command line tools like ‘top’ or ‘ps’.
But none of these tools provide a real-time graph to profile a specific application:

  • Activity Monitor has no graph view which makes it difficult to see how the process’ performance evolves over time.
  • The ‘Activity Monitor’ template of Instruments only monitors the system workload but not the workload of a specific application.

Cornichon System Requirements

  • Mac OS X 10.5.8 or later.
  • Universal application (for both Intel and PowerPC-based Macs).

FAQ


Determining the running kernel mode on 10.6

Posted: March 6th, 2010 | Author: | Filed under: macOS, Programming | Tags: , , , , , , , | 1 Comment »

It might be useful in some cases to know if the MacOS kernel is running in the 32-bit or 64-bit (K64) mode. This is useful for example if you write an application like ‘System Profiler’ that displays the details of the currently running system:

'System Software Overview' in the 'System Profiler' app

Obviously this post only applies to intel machines running on Snow Leopard (see my previous post ‘Intel 64-bit summary’). To simplify the code, I assume that you compiled your application with the 10.6 SDK.

In the IOKit framework on 10.6 the function OSKextGetRunningKernelArchitecture is defined as followed in the OSKext.h header:


/*!
 * @function OSKextGetRunningKernelArchitecture
 * @abstract Returns the architecture of the running kernel.
 *
 * @result
 * The architecture of the running kernel.
 * The caller does not own the returned pointer and should not free it.
 *
 * @discussion
 * This function consults the kernel task and returns a pointer to the
 * NXArchInfo struct representing its architecture.
 * The running kernel's architecture does not necessarily match that
 * of user space tasks (for example, a 32-bit user space task could be
 * running with a 64-bit kernel, or vice-versa).
 */
CF_EXPORT const NXArchInfo *
OSKextGetRunningKernelArchitecture(void)
                AVAILABLE_MAC_OS_X_VERSION_10_6_AND_LATER;

This function is the one I use to determine the current running kernel mode:

#import <Foundation/Foundation.h>
#import <mach-o/arch.h>

// OSKextGetRunningKernelArchitecture is not available in
// the 10.6 SDK headers, but exported since 10.6.
extern const NXArchInfo *OSKextGetRunningKernelArchitecture(void);

static BOOL Is64BitKernel()
{
	BOOL isK64 = NO;
	
	const NXArchInfo *archInfo = OSKextGetRunningKernelArchitecture();
	if (archInfo != NULL)
	{
		isK64 = ((archInfo->cputype & CPU_ARCH_ABI64) != 0);
	}
	
    return isK64;
}

int main (int argc, const char * argv[])
{
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
	
	fprintf(stderr, "Is 64-bit kernel: %d\n", Is64BitKernel());
   
    [pool drain];
    return 0;
}

And don’t forget to link against the IOKit framework.

Also note that it is quite easy to make the previous code compiling with the 10.5 (or earlier) SDK by dynamically getting the address of the OSKextGetRunningKernelArchitecture function and checking if the address is not NULL.


‘Open in 32-bit mode’ – ‘Open using Rosetta’

Posted: January 30th, 2010 | Author: | Filed under: macOS, Programming | Tags: , , , , , , , , | No Comments »

As you know, it is possible to force an Universal Binary (ppc, i386, x86_64) to run in 32-bit mode (i386) even if the machine could run x86_64 binaries. And you can even force the application to run in Rosetta (ppc). To select in which mode the application should run, simply display the info of the application in the Finder and you should see 2 checkboxes:

  • Open in 32-bit mode
  • Open using Rosetta

As far as I know, the first checkbox should always be visible on an Intel machine as long as the application binary contains the x86_64 and i386 architecture.

The Rosetta checkbox will only be visible on an Intel machine if the application binary contains the ppc architecture. Note also that the developer can prevent the checkbox to appear in the Finder by setting the key ‘LSRequiresNativeExecution‘ to true in the ‘Info.plist’ file.

'Open in 32-bit mode' checkbox in the Finder

You may wonder where these flags are stored on the machine. You might have noticed that if you set one flag on an application, trash the application and the preferences, and reinstall it, the flag will still be set. So the flag is definitively not stored in the application package or in the application preferences.

In fact the flags are stored in the file ‘com.apple.LaunchServices.plist’ in the user Preferences folder (~/Library/Preferences/com.apple.LaunchServices.plist). That means that several users on the same machine could have different flags set for the same applications.

Before looking at this file, let’s imagine you have an application called ‘MyApp’ which was compiled for the ppc, i386 and x86_64 architectures. In the Finder you can duplicate this application 2 times. For one instance, check the ‘run in 32-bit mode’, force another instance to run in Rosetta, and leave the original instance unchanged (run as x86_64):

The same application but different checkbox selected in the Finder

Here is what you will see if you open now the file ‘~/Library/Preferences/com.apple.LaunchServices.plist’ with Property List Editor:

The content of the file com.apple.LaunchServices.plist

It’s fairly easy to understand how the flags are stored. The file contains a dictionary ‘LSArchitecturesForX86_64’. The keys of this dictionary are the applicationIDs (‘org.timac.MyApp’ for example). For each applicationID, there is an array containing the information for the different instances of the application. The information of each instance is a pair (path of the application, architecture of the application):

  • The first item in the array is an alias to the first instance of application.
  • The second item is the architecture of the first instance of the application.
  • The third item is an alias to the second instance of application.
  • The fourth is the architecture of the second instance of the application.

Following is the source code for a small application that will read the content of the file ‘com.apple.LaunchServices.plist’ and will print the paths of each application whose flags (‘Open in 32-bit mode’ or ‘Open using Rosetta’) were changed in the Finder. It will also display the architecture selected in the Finder for each of the application. This application will output something like:

applicationID: org.timac.MyApp

Path: /Applications/MyApp.app
will run as: x86_64

Path: /Applications/MyApp 32-bit.app
will run as: i386

Path: /Applications/MyApp Rosetta.app
will run as: ppc

The source code:


#import <Foundation/Foundation.h>

// This function takes as parameter the data of the aliases
// stored in the com.apple.LaunchServices.plist file.
// It returns the resolved path as string.
static NSString *getResolvedAliasPath(NSData* inData)
{
	NSString *outPath = nil;
	if(inData != nil)
	{
		const void *theDataPtr = [inData bytes];
		NSUInteger theDataLength = [inData length];
		if(theDataPtr != nil && theDataLength > 0)
		{
			// Create an AliasHandle from the NSData
			AliasHandle theAliasHandle;
			theAliasHandle = (AliasHandle)NewHandle(theDataLength);
			bcopy(theDataPtr, *theAliasHandle, theDataLength);
			
			FSRef theRef;
			Boolean wChang;
			OSStatus err = noErr;
			err = FSResolveAlias(NULL, theAliasHandle, &theRef, &wChang);
			if(err == noErr)
			{
				// The path was resolved.
				char path[1024];
				err = FSRefMakePath(&theRef, (UInt8*)path, sizeof(path));
				if(err == noErr)
					outPath = [NSString stringWithUTF8String:path];
			}
			else
			{
				// If we can't resolve the alias (file not found),
				// we can still return the path.
				CFStringRef tmpPath = NULL;
				err = FSCopyAliasInfo(theAliasHandle, NULL, NULL,
									  &tmpPath, NULL, NULL);
				
				if(err == noErr && tmpPath != NULL)
					outPath = [(NSString*)tmpPath autorelease];
			}
			
			DisposeHandle((Handle)theAliasHandle);
		}
	}
	
	return outPath;
}

// This function prints the architecture for each application
// in the com.apple.LaunchServices.plist file
static void dumpLSArchitecturesForX86_64()
{
	// The path of the com.apple.LaunchServices.plist file.
	NSString *prefsPath = 
			@"~/Library/Preferences/com.apple.LaunchServices.plist";
	prefsPath = [prefsPath stringByExpandingTildeInPath];
	
	NSDictionary *mainDict = 
			[NSDictionary dictionaryWithContentsOfFile:prefsPath];
	if(mainDict != nil)
	{
		// We are only interested by the
		// "LSArchitecturesForX86_64" dictionary.
		NSDictionary *architectureDict = 
				[mainDict objectForKey:@"LSArchitecturesForX86_64"];
		
		// Get the list of applications.
		// The array is ordered by applicationID.
		NSArray *applicationIDArray = [architectureDict allKeys];
		if(applicationIDArray != nil)
		{
			// For each applicationID
			NSUInteger i = 0;
			for(i = 0 ; i < [applicationIDArray count] ; i++)
			{
				NSString *applicationID =
						[applicationIDArray objectAtIndex:i];
				
				NSArray *appArray =
						[architectureDict objectForKey:applicationID];
				
				NSLog(@"-------------------------");
				NSLog(@"applicationID: %@", applicationID);
				
				// For each instance of the application,
				// there is a pair (Alias, architecture).
				// The alias is stored as a NSData
				// and the architecture as a NSString.
				NSUInteger j = 0;
				for(j = 0 ; j < [appArray count] / 2 ; j++)
				{
					NSLog(@"\n");
					
					// Just for safety
					if(j * 2 + 1 < [appArray count])
					{
						NSData *aliasData =
							[appArray objectAtIndex:j * 2];
						
						NSString *theArch =
							[appArray objectAtIndex:j * 2 + 1];
						
						if(aliasData != nil && theArch != nil)
						{
							// Get the path of the application
							NSString *resolvedPath =
										getResolvedAliasPath(aliasData);
							
							NSLog(@"\t Path: %@", resolvedPath);
							NSLog(@"\t will run as: %@", theArch);
						}
					}
				}
			}
		}
	}
}

int main (int argc, const char * argv[])
{
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
    
	dumpLSArchitecturesForX86_64();
		
	[pool drain];
    return 0;
}