Category Archives: programming

First-chance exception at {address} (ntdll.dll) in {exename}.exe: 0xC0000139: Entry Point Not Found

Writing a plugin for a Windows application using Visual Studio?

You had the smarts to define the application’s exe as the debug executable in Visual Studio project options?

While reading the output, you saw the error from the post’s title?

First-chance exception at 
(ntdll.dll) in .exe: 0xC0000139: Entry Point Not Found

You’ve probably got a classic case of app-uses-one-version-of-dll-while-one-of-my-plugin’s-dependencies-wants-another-one. In my case, I had to replace zlib1.dll in the app with the one that came with Igor Zlatković’s Win32 builds of libxml2, xmlsec, etc.

Read a bit more about the error, including different causes.

Symbolicating Mac app's crash reports — manually

You will need your released app’s dSYM bundle. Since you are a good developer, whenever you release a version of your software, you use Xcode’s built in Archive functionality, so you don’t have a problem with that. (Right?)

So open Xcode’s Organizer. Right click on your archive, and pick “Show in Finder.” Then right click on the archive, and choose “Show Package Contents”.

Enter the “dSYMs” subfolder, and find the sole .dSYM bundle in there. Right click on it, and “Show Package Contents”. Open Contents, Resources, DWARF — and you’ll reach the file that actually contains the debug symbols. For example, “GeorgesGreatApp”, without any extension. Wheeee!

Now, open Terminal. Punch in atos -o and drag and drop the “GeorgesGreatApp” file (the one that contains the debug symbols) into the terminal. Then punch in -arch x86_64 (or whatever architecture the crash occurred on). Finally, paste the address that you want to know more about.

For example, given the following line in the crash log:

1   net.vucica.GeorgesGreatApp    	0x0000000100001e91 0x100000000 + 7825

you’d take the first hex number that appears on that line, and have this on the command line:

atos -o /Users/YOURUSERNAME/Library/Developer/Xcode/Archives/2012-02-29/GeorgesGreatApp\ 29.02.2012.\ 00.40.xcarchive/dSYMs/GeorgesGreatApp.app.dSYM/Contents/Resources/DWARF/GeorgesGreatApp -arch x86_64 0x0000000100001e91

and you’d get this output:

-[GGAppDelegate generateThumbnailsForJpeg:] (in GeorgesGreatApp) (GGAppDelegate.m:326)

Extremely handy when Xcode screws up symbolication or outright refuses to import the crash log. Maybe it’s Xcode’s fault. Maybe Spotlight did not correctly index dSYM’s location. Maybe Spotlight did not correctly index .app’s archived location. Whatever it is, I don’t really care — if symbolication is broken, it’s broken. But at least I can use the underlying mechanism in atos.

Dokumentacija o mrežnom protokolu i datotečnom formatu za fiskalnu blagajnu

Dokumentacija se, zanimljivo, ne nalazi na FINAinom webu o fiskalizaciji, nego na webu porezne uprave.

Zato jer, je li, logično je da se koristi PKI arhitektura FINAe i podnose zahtjevi FINAi i zatim sve submita poreznoj upravi.

Dakle, file format za XML datoteku, postupak potpisivanja (hura, signing) i network protokol. Hura – here’s to reading massive amounts of boring stuff! Hura za nove poreze, hura za FINA-u i hura za vrle nam ministre…

Installing IMAP extension for PHP on Mountain Lion

Based on Dao Hoang Son’s tutorial (itself based on Dan Spencer’s Lion tutorial), as well as a few corrections of my own, I came up with the following script. It fetches and installs University of Washington’s IMAP library, then the PCRE – Perl Compatible Regular Expressions library, and finally the PHP IMAP extension itself.

Please study the script yourself before running it, or run it line by line. It performs no error checking, meaning it might totally wreck your machine — and I’m not responsible if it does. Keep a Time Machine backup around and unplugged from the computer, in case it does.

The script wasn’t yet tested in its complete form; it’s an approximate transcript of commands I ran in shell. But since I’ll keep it around in case I ever need to re-run it, I’m fairly certain it works.

UPDATE December 24th 2012 – Merry Christmas! I’ve applied corrections based on Mehmet’s comment. He also comments you need to install autoconf before running the script (so phpize can work). I already had it installed.

Filesizes for stuff I downloaded: 1.990.304 – imap-2007f.tar.gz, 1.539.766 – pcre-8.20.tar.gz, 12.926.535 – PHP-5.3.15.tar.gz

#!/bin/bash
BUILDDIR=/tmp/phpimapmountainlion

mkdir "$BUILDDIR"
echo " "
echo "= FETCHING AND INSTALLING IMAP"
echo " "
cd "$BUILDDIR"
wget -c ftp://ftp.cac.washington.edu/imap/imap-2007f.tar.gz
rm -rf imap-2007f
tar xvvfz imap-2007f.tar.gz
cd imap-2007f
make osx EXTRACFLAGS="-arch i386 -arch x86_64 -g -Os -pipe -no-cpp-precomp"
sudo mkdir -p /usr/local/imap-2007f/include
sudo cp c-client/*.h /usr/local/imap-2007f/include
sudo mkdir -p /usr/local/imap-2007f/lib
sudo cp c-client/c-client.a /usr/local/imap-2007f/lib/libc-client.a

echo " "
echo "= FETCHING AND INSTALLING PCRE"
echo " "
cd "$BUILDDIR"
wget "http://sourceforge.net/projects/pcre/files/pcre/8.20/pcre-8.20.tar.gz"
rm -rf pcre-8.20
tar xvvfz pcre-8.20.tar.gz
cd pcre-8.20
./configure --prefix=/usr/local
make
sudo make install

echo " "
echo "= FETCHING AND INSTALLING PHP-IMAP"
echo " "
cd "$BUILDDIR"
PHPVERSION=`php --version|head -n1|cut -f 2 -d ' '`
##git clone -b "PHP-$PHPVERSION" https://github.com/php/php-src.git php-src
wget --no-check-certificate -c https://github.com/php/php-src/tarball/PHP-5.3.15 -O PHP-5.3.15.tar.gz
tar xvvfz PHP-5.3.15.tar.gz
cd `ls |grep php-php-src-|head -n1`
cd ext/imap
phpize
./configure --with-imap=/usr/local/imap-2007f --with-kerberos --with-imap-ssl
make
sudo cp modules/imap.so /usr/lib/php/extensions/no-debug-non-zts-20090626/

Mini-explanation of BFS and DFS

Disclaimer: all code in this post is untested-as-posted, but hopefully illustrates some basic concepts. Also, compared to a few of the folks I know, I suck at “algorithmic problems” such as these (i.e. those used on algorithm competitions such as IOI, Code Jam, Topcoder, etc) – so the solutions are almost certainly suboptimal. Post your own solutions in comments.

So you need to perform a search within fenced area in a 2D array of data. Searching includes counting for objects you want to find and flood-filling this area. Think “bucket” in various raster painting programs that fill pixels until reaching a fence – a “different” color. There are two primary algorithms to do this.

Depth-first search

DFS or depth first search goes as deep as possible in a particular direction before reaching fence and backing off just as much is needed to change the direction. It’s implemented using a stack. Due to this, it commonly involves simply using recursion to explore surroundings of the “current” tile. (Let’s use “tile” as a name for cells of a 2D array.) Each tile is an entry on the stack — when implemented via recursion, it’s a single function call or a ‘stack frame’.

In the code below, I’ll be using a one-dimensional array. Two-dimensional arrays have… semantical particularities that I prefer to avoid.

#define WIDTH 16
#define HEIGHT 7
char field[WIDTH*HEIGHT] = 
  "................" // This is a single string.
  "...#######.###.." // It's perfectly valid to break them like this.
  "..##.....###.#.." // Also, never forget: C strings are arrays of characters.
  "..#..........#.."
  "..############.."
  "..#.#..........."
  "..###...........";

void dfs(int x, int y)
{
  if(field[y*WIDTH + x] != '.')
  {
    // we can't do anything here, tile is not 'empty'.
    return;
  }
  
  // do whatever you want to do here...
  // for example, fill tile with a different character.
  // in your paint program, that'd be a different color
  field[y*WIDTH + x] = '!';

  // now let's spread further.
  // in case we should not have spread there, we'll
  // abort when we get there.
  dfs(x, y-1); // up
  dfs(x, y+1); // down
  dfs(x-1, y); // left
  dfs(x+1, y); // right;
}

int main()
{
  dfs(6, 3);
  return 0;
}

Before utilizing this algorithm, consider that stack may not be as large as you may want it to be, so recursively calling like this might not be a good idea.

dfs(6, 3) makes the algorithm begin somewhere within the large fenced area. (Can you figure out where?) As implemented, it paints the current tile, goes up, paints the current tile, goes up, gives up and steps back, goes down, gives up and steps back, goes left, paints the current tile, goes up, gives up and steps back, goes down, fills the current tile, goes up, gives up and steps back, goes down, gives up and steps back, …

In other words, take a piece of paper and a pencil, and trace the algorithm yourself.

Algorithm terminates when all four tests have failed (and it’s bound to happen eventually, since you’ve been coloring the tiles you’ve covered all along).

If you’re not modifying underlying data, you’ll want to have an additional array filled with “not covered” marks (e.g. boolean value of false – perhaps memset() to zero). As you pass certain tiles, you mark them as having been handled, and you use the “must be not covered” as an additional fencing condition.

Breadth-first search

BFS or breadth first search has a somewhat more natural search order. Like a bucket of spilt water, it spreads from the point where it started, instead of weirdly going into a single direction, then spreading around while it’s backing off. (Again, use paper and pencil and draw both algorithms if you can’t visualize the behavior.)

BFS involves the use of a queue in place of a stack. It can’t be implemented recursively; instead, you can think of it as a “list of tasks we want to execute in the future, first come, first served” (or FIFO – first in, first out).

So, since the earliest tiles were queued earliest, they’ll be processed earliest.

In this example, I’ll only show you the new bfs() function. For implementing the queue, I’ll use STL vectors, since I’m too lazy to code queue myself and I’m too lazy to look up a proper data structure offered in STL.

struct bfs_task // define data type "bfs_task".
{
  int x, y;
};

void bfs(int x, int y)
{
  std::vector bfs_queue;

  // add initial position to the task queue
  bfs_queue.push_back((bfs_task){.x = x, .y = y});

  // start rolling over the queue.
  // not using iterators since we'll be modifying the vector,
  // which would break the iterators.
  while (bfs_queue.size()) // at least one task in the queue
  {
    bfs_task currentTask = bfs_queue[0];
    int x = currentTask.x, y = currentTask.y;

    // remove the first task
    bfs_queue.erase(bfs_queue.begin(), bfs_queue.begin()+1); 
    // note! the line before actually copies everything "one element up".
    // but I'm too lazy to look up an optimal STL template to use.
    // I don't use C++ daily anymore, and this was a quickly written post.

    // can we be here? if not, skip
    if(field[y*WIDTH + x] != '.')
    {
      // we can't do anything here, tile is not 'empty'.
      return;
    }

    // do whatever you want to do here...
    // for example, fill tile with a different character.
    // in your paint program, that'd be a different color
    field[y*WIDTH + x] = '!';

    // now let's spread further.
    // in case we should not have spread there, we'll
    // abort when we get there.
    // please note: we're actually just queueing tasks for future use.
    bfs_queue.push_back((bfs_task){.x = x, .y = y-1}); // up
    bfs_queue.push_back((bfs_task){.x = x, .y = y+1}); // down
    bfs_queue.push_back((bfs_task){.x = x-1, .y = y}); // left
    bfs_queue.push_back((bfs_task){.x = x+1, .y = y}); // right
  }
}

Once again: std::vector is a bad data structure to use here due to slow .erase().

Breadth-first search on Wikipedia
Depth-first search on Wikipedia

Exploring Apple's customization of titlebar in Xcode 4

As you may have noticed, Xcode’s NSWindow does not actually have a single representedURL; it has two, the project and the current in-project file.

So how did Apple achieve that?

First things first, you can start figuring that out by yourself by asking your window’s contentView for its superview. Although undocumented, enough apps seem to be playing around with this (including Xcode) that I presume Apple would be reluctant to change something important here.

Second, I’m not going to actually show you any code just yet. Perhaps in a future blog post; I did start writing something, but it’s unfinished.

Third, there is no third: let’s get to it.

Hacking tools

Playing with contentView‘s superviews can only get you so far (although, you may be able to hack something anyway). Injecting code in form of plugins into Xcode is possible, as proven by JugglerShu’s XVim.

But there’s a nicer way.

Say hello to F-Script. It’s a nice scripting language and let’s-call-it mini-IDE in itself, but there’s something far more powerful it can do.

On F-Script

It has a full fledged object browser that uses introspection to figure out what the hell exists in the view hierarchy. It also has a nice view picker so you can easily access the exact view that you’re playing with. Python may be neat for programming, but this one is just smashing for debugging GUI apps.

F-Script is not intended to be used as a standalone dev environment however; you’re supposed to put it into your app and use it at runtime. Kind of like what you can do with Python already… except this one comes with a runtime debugging GUI out of the box (and the aforementioned view picker!), and is pretty dedicated to playing with Cocoa and Objective-C (while Python can play with it through its PyObjC bridge – powerful, but not the best way to do it; also, method names become lengthy and weird when written in Python).

Note that I, for now, have absolutely no experience with F-Script as a programming language, and I don’t intend to learn it too much for now, just as I don’t intend to learn all nuts and bolts of GDB. It may be nice, but for now, it’s far, far, far more amazing as a debugging tool.

Okay, so where does playing with Xcode come in?

Unfortunately, not in the form of injecting the debugging code into Xcode and playing with it. This is the loveliest part of F-Script, however; you can inject it into any app and inspect how it works, see runtime class definitions, send messages to existing objects, etc. But not with Xcode, because of some magic that Xcode is doing causing F-Script to crash Xcode.

Side note: injection of F-Script is done via gdb. The F-Script Anywhere automator workflow intended to be put into ~/Library/Services actually consists of figuring out frontmost app’s process ID, constructing some gdb commands and running gdb. gdb commands used involve attach to existing process, then calling Objective-C method -[NSBundle load] on /Library/Frameworks/FScript.framework, and finally calling +[FScriptMenuItem insertInMainMenu] and detaching. Quite ingenious!

Finding the beast

Let’s get back to business. Although Xcode crashes, view inspector of F-Script works long enough to let us know the name of the class implementing the custom view Apple uses in the titlebar for displaying two “represented URLs”. A-ha! DVTDualProxyWindowTitleView, we’ve found you!

Now, where could this be defined? Let’s explore various private frameworks found in Xcode using class-dump (install it from MacPorts). And voila! Xcode.app/Contents/SharedFrameworks/DVTKit.framework. Using class-dump we can also see that it’s used in… DVTDualProxyWindow, a subclass of NSWindow. Wonderful!

Now, just trying to load this framework into standalone F-Script.app fails miserably and returns NO. At least for me. otool -L told me which frameworks this one depends on… so I loaded them first.

About the beast

Finally, DVTDualProxyWindow is a subclass of NSWindow which apparently overrides -setTitle: to do nothing, overrides -setRepresentedURL: to be used for the ‘project’ URL, and defines new method -setSecondaryRepresentedURL: to add the ‘document’ URL. Both of these methods are just talking to DVTDualProxyWindowTitleView. We don’t really care what happens behind the scenes; it’s just a regular view. But let’s see if it works.

Open F-Script app. Right click on the toolbar and choose ‘Customize’. Aside from customization sheet, a new window appears titled ‘Custom Buttons’. Pick one of ‘CustomX’ buttons, and select ‘Block…’. (Of course, prior to that, in the toolbar customization sheet, drag the picked button to the toolbar… you know, so you can click it.)

Now, paste in the following code.

Testing the beast

[:selectedObject | 



(NSBundle bundleWithPath:'/Applications/Xcode.app/Contents/SharedFrameworks/DVTFoundation.framework') load.

(NSBundle bundleWithPath:'/System/Library/PrivateFrameworks/DataDetectorsCore.framework') load.

(NSBundle bundleWithPath:'/System/Library/PrivateFrameworks/DataDetectors.framework') load.
(NSBundle bundleWithPath:'/System/Library/Frameworks/SecurityInterface.framework') load.
(NSBundle bundleWithPath:'/System/Library/Frameworks/Carbon.framework') load.
(NSBundle bundleWithPath:'/System/Library/Frameworks/CoreServices.framework') load.

errorPointer := FSObjectPointer objectPointer.
(NSBundle bundleWithPath:'/Applications/Xcode.app/Contents/SharedFrameworks/DVTKit.framework') loadAndReturnError:errorPointer.


" printing out an error: 
   errorPointer at:0.
"

"win := ((DVTDualProxyWindow alloc) init)."

win := DVTDualProxyWindow alloc initWithContentRect:(125<>513 extent:383<>175)
                                   styleMask:NSTitledWindowMask + NSClosableWindowMask + NSMiniaturizableWindowMask + NSResizableWindowMask
                                     backing:NSBackingStoreBuffered
                                       defer:NO.

(win setRepresentedURL:(NSURL fileURLWithPath:'/Applications/Xcode.app')).
(win setSecondaryRepresentedURL:(NSURL fileURLWithPath:'/Applications/Xcode.app')).



"Instantiate a button, put it in the window and configure it"
button := NSButton alloc initWithFrame:(247<>15 extent:90<>30).
win contentView addSubview:button.
button setBezelStyle:NSRoundedBezelStyle.
button setTitle:'Boo'.
button setKeyEquivalent:'\r'.

"An example of using F-Script blocks to handle click on button. Ignore it."
conversionScript := [(form cellAtIndex:2) setStringValue:(form cellAtIndex:0) floatValue * (form cellAtIndex:1) floatValue].

" From docs: "
"The [...] notation creates an object of class Block which represents a block of code that can be executed later (Block is an Objective-C class provided by the F-Script framework). In our block, we simply get the values of the fields in the user interface objects, perform the computation (simply involves multiplication) and put the result in a UI element.
"

"An example on how to add handling for button click. Ignore it."
"Make the script the target of the button.
The script will be evaluated when the user presses the button"
button setTarget:conversionScript.
button setAction:#value.


"Show window"
(win orderFront:nil).



]

Click on the ‘Run’ button, and type in ‘nil‘. (You don’t really care about the selectedObject, but I did not study F-Script long enough to avoid it.)

Hopefully this gives you enough idea to debug with, explore with, as well as an idea on how to implement dual-representedURL windows. Good luck and have fun! 🙂