Search code examples
pdfcore-graphicsosx-mountain-lionexc-bad-access

CGContextDrawPDFPage crashes randomly with EXC_BAD_ACCESS on OS X 10.8


My application takes a PDF and generate thumbnails for a given number of pages.

Everything is fine on OS X 10.7

On OS X 10.8, on some pages, on some PDFs (on 1400 tested the count is 7 documents with a single "offending" page) it fails to render resulting in an EXC_BAD_ACCESS when calling CGContextDrawPDFPage

Sometimes (1 over 10) it succeed. But 90% of the time that page on that document causes a crash.

The relevant code, posted below, is repeated in a loop for each pageNumber to be rendered of the pdfDocument provided. Each iteration produces a CGImageRef imgRef that is saved into an array and used later.


Suppose crash happens on page 30.

If I render from 28 to 38 is ok.

If I render from 27 to 37 crash.

If I render just 30 is always ok.

Some sets of pages, containing the offending one, crash. Other don't.


It seem to be a bug in PDFKit 10.8... (messing things up while trying to do some internal caching optimization when asked to render multiple pages of the same document?)

Of course I can't exclude a bug in my code but it seem very unlikely.

Any idea of how to work this around will be appreciated.

    CGPDFPageRef     pdfPage      =   CGPDFDocumentGetPage 
                                            ( pdfDocument,
                                              pageNumber );

    if( !pdfPage ) return;

    CGPDFPageRetain(pdfPage);

    CGRect          rect          =   CGPDFPageGetBoxRect
                                            ( pdfPage,
                                              kCGPDFCropBox);

    CGColorSpaceRef imgColorSpace =   CGColorSpaceCreateDeviceRGB ( );

    CGContextRef    contextRef    =   CGBitmapContextCreate
                                            ( NULL,
                                              (size_t) (rect.size.width),
                                              (size_t) (rect.size.height),
                                              8,
                                              ((size_t) (rect.size.width))*4,
                                              imgColorSpace,
                                              kCGImageAlphaPremultipliedLast );

    CGColorSpaceRelease ( imgColorSpace );
    if( !contextRef ) return;

    CGContextDrawPDFPage ( contextRef, pdfPage ); // <==== EXC_BAD_ACCESS

    CGImageRef      imgRef        =   CGBitmapContextCreateImage
                                            ( contextRef );

    CFRelease ( contextRef );

    CGPDFPageRelease( pdfPage );

Solution

  • It is a bug of PDFKit introduced in OS X 10.8

    The bug has been fixed in OS X 10.9