return reference to cache instead of copying the mask

BUG=437128

Review URL: https://codereview.chromium.org/889303005
diff --git a/src/core/SkMask.cpp b/src/core/SkMask.cpp
index 4ae65c7..1115080 100644
--- a/src/core/SkMask.cpp
+++ b/src/core/SkMask.cpp
@@ -7,6 +7,8 @@
 
 #include "SkMask.h"
 
+//#define TRACK_SKMASK_LIFETIME
+
 /** returns the product if it is positive and fits in 31 bits. Otherwise this
     returns 0.
  */
@@ -30,10 +32,17 @@
     return size;
 }
 
+#ifdef TRACK_SKMASK_LIFETIME
+    static int gCounter;
+#endif
+
 /** We explicitly use this allocator for SkBimap pixels, so that we can
     freely assign memory allocated by one class to the other.
 */
 uint8_t* SkMask::AllocImage(size_t size) {
+#ifdef TRACK_SKMASK_LIFETIME
+    SkDebugf("SkMask::AllocImage %d\n", gCounter++);
+#endif
     return (uint8_t*)sk_malloc_throw(SkAlign4(size));
 }
 
@@ -41,6 +50,11 @@
     freely assign memory allocated by one class to the other.
 */
 void SkMask::FreeImage(void* image) {
+#ifdef TRACK_SKMASK_LIFETIME
+    if (image) {
+        SkDebugf("SkMask::FreeImage  %d\n", --gCounter);
+    }
+#endif
     sk_free(image);
 }
 
diff --git a/src/core/SkMaskFilter.cpp b/src/core/SkMaskFilter.cpp
index c9783e7..ee58b74 100644
--- a/src/core/SkMaskFilter.cpp
+++ b/src/core/SkMaskFilter.cpp
@@ -10,6 +10,7 @@
 #include "SkMaskFilter.h"
 #include "SkBlitter.h"
 #include "SkDraw.h"
+#include "SkCachedData.h"
 #include "SkRasterClip.h"
 #include "SkRRect.h"
 #include "SkTypes.h"
@@ -20,6 +21,15 @@
 #include "SkGrPixelRef.h"
 #endif
 
+SkMaskFilter::NinePatch::~NinePatch() {
+    if (fCache) {
+        SkASSERT((const void*)fMask.fImage == fCache->data());
+        fCache->unref();
+    } else {
+        SkMask::FreeImage(fMask.fImage);
+    }
+}
+
 bool SkMaskFilter::filterMask(SkMask*, const SkMask&, const SkMatrix&,
                               SkIPoint*) const {
     return false;
@@ -219,7 +229,6 @@
         return false;
     }
     draw_nine(patch.fMask, patch.fOuterRect, patch.fCenter, true, clip, blitter);
-    SkMask::FreeImage(patch.fMask.fImage);
     return true;
 }
 
@@ -234,9 +243,7 @@
     if (rectCount > 0) {
         NinePatch patch;
 
-        patch.fMask.fImage = NULL;
-        switch (this->filterRectsToNine(rects, rectCount, matrix,
-                                        clip.getBounds(), &patch)) {
+        switch (this->filterRectsToNine(rects, rectCount, matrix, clip.getBounds(), &patch)) {
             case kFalse_FilterReturn:
                 SkASSERT(NULL == patch.fMask.fImage);
                 return false;
@@ -244,7 +251,6 @@
             case kTrue_FilterReturn:
                 draw_nine(patch.fMask, patch.fOuterRect, patch.fCenter, 1 == rectCount, clip,
                           blitter);
-                SkMask::FreeImage(patch.fMask.fImage);
                 return true;
 
             case kUnimplemented_FilterReturn: