-
Notifications
You must be signed in to change notification settings - Fork 3.9k
Cap iOS HEIC/image decode dimensions to prevent OOM #94969
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
dilshodmackbook-sketch
wants to merge
8
commits into
Expensify:main
from
dilshodmackbook-sketch:dilshod/fix-93846-heic-oom
Closed
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
2b7e31b
fix: cap iOS HEIC decode dimensions and sequence multi-select to prev…
dilshodmackbook-sketch 18efe9c
test: cover getBoundedImageResize iOS-only decode cap
dilshodmackbook-sketch 7f2aad9
fix: bound cropped output in cropOrRotateImage to keep large crops of…
dilshodmackbook-sketch 36278e8
refactor: keep multi-select concurrent; sequencing moves to a follow-…
dilshodmackbook-sketch 36bd217
test: reword comment to satisfy cspell (avoid 'upscales')
dilshodmackbook-sketch 9d1e819
test: cover the decode cap in heicConverter and cropOrRotateImage
dilshodmackbook-sketch 716e8dd
Merge branch 'main' into dilshod/fix-93846-heic-oom
dilshodmackbook-sketch 911fa12
style: run oxfmt 0.55.0 on cropOrRotate/getBoundedImageResize files
dilshodmackbook-sketch File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,48 @@ | ||
| import CONST from '@src/CONST'; | ||
|
|
||
| import {Platform} from 'react-native'; | ||
| import ImageSize from 'react-native-image-size'; | ||
|
|
||
| type BoundedResize = {width: number} | {height: number}; | ||
|
|
||
| /** | ||
| * Returns a resize action that bounds the longest side of an image with the given dimensions to | ||
| * `CONST.MAX_IMAGE_DIMENSION`, or `undefined` when it already fits within that budget (so we never | ||
| * upscale). Resizing with only one side preserves the aspect ratio, so bounding the longer side is enough. | ||
| * | ||
| * The cap exists to keep `ImageManipulator`'s `renderAsync()` from materializing an oversized bitmap | ||
| * (`width × height × 4` bytes) in one contiguous native buffer. On iOS HybridApp — where NewDot shares a | ||
| * single jetsam memory budget with the resident OldDot — a large decode is exactly the allocation that | ||
| * triggers the `std::bad_alloc` OOM crash. It is a no-op off iOS, leaving other platforms untouched. | ||
| */ | ||
| function getBoundedResizeForDimensions(width: number, height: number): BoundedResize | undefined { | ||
| // The OOM is specific to iOS HybridApp's shared jetsam budget, so we only cap there (per the issue | ||
| // owner's guidance on #93846). | ||
| if (Platform.OS !== 'ios') { | ||
| return undefined; | ||
| } | ||
|
|
||
| if (Math.max(width, height) <= CONST.MAX_IMAGE_DIMENSION) { | ||
| return undefined; | ||
| } | ||
|
|
||
| return width >= height ? {width: CONST.MAX_IMAGE_DIMENSION} : {height: CONST.MAX_IMAGE_DIMENSION}; | ||
| } | ||
|
|
||
| /** | ||
| * Reads the source dimensions of the image at `uri` and returns the bounding resize action to apply | ||
| * before `renderAsync()` (see `getBoundedResizeForDimensions`). If the dimensions can't be read we fall | ||
| * back to no resize rather than blocking the decode. | ||
| */ | ||
| function getBoundedImageResize(uri: string): Promise<BoundedResize | undefined> { | ||
| if (Platform.OS !== 'ios') { | ||
| return Promise.resolve(undefined); | ||
| } | ||
|
|
||
| return ImageSize.getSize(uri) | ||
| .then(({width, height}) => getBoundedResizeForDimensions(width, height)) | ||
| .catch(() => undefined); | ||
| } | ||
|
|
||
| export {getBoundedResizeForDimensions}; | ||
| export default getBoundedImageResize; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,76 @@ | ||
| import cropOrRotateImage from '@libs/cropOrRotateImage/index.native'; | ||
|
|
||
| import CONST from '@src/CONST'; | ||
|
|
||
| import {ImageManipulator} from 'expo-image-manipulator'; | ||
| import {Platform} from 'react-native'; | ||
| import ImageSize from 'react-native-image-size'; | ||
|
|
||
| jest.mock('react-native-image-size'); | ||
| jest.mock('react-native-blob-util', () => ({ | ||
| __esModule: true, | ||
| default: {fs: {stat: jest.fn(() => Promise.resolve({size: 1024}))}}, | ||
| })); | ||
| jest.mock('expo-image-manipulator', () => { | ||
| const saveAsync = jest.fn(() => Promise.resolve({uri: 'file://cropped.jpg', width: 2400, height: 1800})); | ||
| const renderAsync = jest.fn(() => Promise.resolve({saveAsync})); | ||
| const context = {resize: jest.fn(), crop: jest.fn(), rotate: jest.fn(), renderAsync}; | ||
| return { | ||
| ImageManipulator: {manipulate: jest.fn(() => context)}, | ||
| SaveFormat: {JPEG: 'jpeg', PNG: 'png', WEBP: 'webp'}, | ||
| }; | ||
| }); | ||
|
|
||
| const mockedGetSize = jest.mocked(ImageSize.getSize); | ||
| // `manipulate` returns the same context singleton on every call, so we can capture its action mocks once. | ||
| const probeContext = ImageManipulator.manipulate('probe'); | ||
| /* eslint-disable @typescript-eslint/unbound-method */ | ||
| const resizeMock = jest.mocked(probeContext.resize); | ||
| const cropMock = jest.mocked(probeContext.crop); | ||
| const rotateMock = jest.mocked(probeContext.rotate); | ||
| /* eslint-enable @typescript-eslint/unbound-method */ | ||
|
|
||
| const options = {type: 'image/jpeg', name: 'cropped.jpg', compress: 1}; | ||
|
|
||
| describe('cropOrRotateImage (native)', () => { | ||
| let platformReplaceProperty: jest.ReplaceProperty<string>; | ||
|
|
||
| beforeEach(() => { | ||
| platformReplaceProperty = jest.replaceProperty(Platform, 'OS', 'ios'); | ||
| }); | ||
|
|
||
| afterEach(() => { | ||
| platformReplaceProperty.restore(); | ||
| jest.clearAllMocks(); | ||
| }); | ||
|
|
||
| it('bounds a crop that is still oversized, without dropping the crop action', async () => { | ||
| mockedGetSize.mockResolvedValue({width: 12000, height: 9000}); | ||
| const crop = {originX: 0, originY: 0, width: 8000, height: 6000}; | ||
|
|
||
| await cropOrRotateImage('file://receipt.heic', [{crop}], options); | ||
|
|
||
| expect(cropMock).toHaveBeenCalledWith(crop); | ||
| expect(resizeMock).toHaveBeenCalledWith({width: CONST.MAX_IMAGE_DIMENSION}); | ||
| }); | ||
|
|
||
| it('does not resize when the cropped output already fits the budget', async () => { | ||
| mockedGetSize.mockResolvedValue({width: 12000, height: 9000}); | ||
| const crop = {originX: 0, originY: 0, width: 1000, height: 800}; | ||
|
|
||
| await cropOrRotateImage('file://receipt.heic', [{crop}], options); | ||
|
|
||
| expect(cropMock).toHaveBeenCalledWith(crop); | ||
| expect(resizeMock).not.toHaveBeenCalled(); | ||
| }); | ||
|
|
||
| it('bounds a rotate-only large image using the rotated dimensions', async () => { | ||
| mockedGetSize.mockResolvedValue({width: 8000, height: 6000}); | ||
|
|
||
| await cropOrRotateImage('file://photo.heic', [{rotate: 90}], options); | ||
|
|
||
| expect(rotateMock).toHaveBeenCalledWith(90); | ||
| // After a 90° rotate the 8000×6000 source becomes 6000×8000, so the taller side is bounded. | ||
| expect(resizeMock).toHaveBeenCalledWith({height: CONST.MAX_IMAGE_DIMENSION}); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,142 @@ | ||
| import getBoundedImageResize, {getBoundedResizeForDimensions} from '@libs/getBoundedImageResize'; | ||
|
|
||
| import CONST from '@src/CONST'; | ||
|
|
||
| import {Platform} from 'react-native'; | ||
| import ImageSize from 'react-native-image-size'; | ||
|
|
||
| jest.mock('react-native-image-size'); | ||
|
|
||
| const mockedGetSize = jest.mocked(ImageSize.getSize); | ||
| const MAX = CONST.MAX_IMAGE_DIMENSION; | ||
|
|
||
| describe('getBoundedImageResize', () => { | ||
| afterEach(() => { | ||
| jest.clearAllMocks(); | ||
| }); | ||
|
|
||
| describe('on non-iOS platforms', () => { | ||
| const nonIOSPlatforms = ['android', 'web', 'macos', 'windows'] as const; | ||
|
|
||
| describe.each(nonIOSPlatforms)('%s', (platform) => { | ||
| let platformReplaceProperty: jest.ReplaceProperty<string>; | ||
|
|
||
| beforeEach(() => { | ||
| platformReplaceProperty = jest.replaceProperty(Platform, 'OS', platform); | ||
| }); | ||
|
|
||
| afterEach(() => { | ||
| platformReplaceProperty.restore(); | ||
| }); | ||
|
|
||
| it('returns undefined without reading the image size (the cap is iOS-only)', async () => { | ||
| const result = await getBoundedImageResize('file://photo.heic'); | ||
|
|
||
| expect(result).toBeUndefined(); | ||
| expect(mockedGetSize).not.toHaveBeenCalled(); | ||
| }); | ||
| }); | ||
| }); | ||
|
|
||
| describe('on iOS', () => { | ||
| let platformReplaceProperty: jest.ReplaceProperty<string>; | ||
|
|
||
| beforeEach(() => { | ||
| platformReplaceProperty = jest.replaceProperty(Platform, 'OS', 'ios'); | ||
| }); | ||
|
|
||
| afterEach(() => { | ||
| platformReplaceProperty.restore(); | ||
| }); | ||
|
|
||
| it('returns undefined when the image already fits within the budget (so it does not upscale)', async () => { | ||
| mockedGetSize.mockResolvedValue({width: 1200, height: 800}); | ||
|
|
||
| const result = await getBoundedImageResize('file://small.heic'); | ||
|
|
||
| expect(result).toBeUndefined(); | ||
| }); | ||
|
|
||
| it('returns undefined when the longest side equals the budget (boundary is inclusive)', async () => { | ||
| mockedGetSize.mockResolvedValue({width: MAX, height: 1000}); | ||
|
|
||
| const result = await getBoundedImageResize('file://exact.heic'); | ||
|
|
||
| expect(result).toBeUndefined(); | ||
| }); | ||
|
|
||
| it('caps the width for a landscape image that exceeds the budget', async () => { | ||
| mockedGetSize.mockResolvedValue({width: 8000, height: 6000}); | ||
|
|
||
| const result = await getBoundedImageResize('file://landscape.heic'); | ||
|
|
||
| expect(result).toEqual({width: MAX}); | ||
| }); | ||
|
|
||
| it('caps the height for a portrait image that exceeds the budget', async () => { | ||
| mockedGetSize.mockResolvedValue({width: 6000, height: 8000}); | ||
|
|
||
| const result = await getBoundedImageResize('file://portrait.heic'); | ||
|
|
||
| expect(result).toEqual({height: MAX}); | ||
| }); | ||
|
|
||
| it('caps the width for a square image that exceeds the budget', async () => { | ||
| mockedGetSize.mockResolvedValue({width: 8000, height: 8000}); | ||
|
|
||
| const result = await getBoundedImageResize('file://square.heic'); | ||
|
|
||
| expect(result).toEqual({width: MAX}); | ||
| }); | ||
|
|
||
| it('falls back to no resize when the image size cannot be read', async () => { | ||
| mockedGetSize.mockRejectedValue(new Error('Could not read image size')); | ||
|
|
||
| const result = await getBoundedImageResize('file://corrupt.heic'); | ||
|
|
||
| expect(result).toBeUndefined(); | ||
| }); | ||
| }); | ||
| }); | ||
|
|
||
| describe('getBoundedResizeForDimensions', () => { | ||
| describe('on non-iOS platforms', () => { | ||
| let platformReplaceProperty: jest.ReplaceProperty<string>; | ||
|
|
||
| beforeEach(() => { | ||
| platformReplaceProperty = jest.replaceProperty(Platform, 'OS', 'android'); | ||
| }); | ||
|
|
||
| afterEach(() => { | ||
| platformReplaceProperty.restore(); | ||
| }); | ||
|
|
||
| it('returns undefined even for an oversized image (the cap is iOS-only)', () => { | ||
| expect(getBoundedResizeForDimensions(8000, 6000)).toBeUndefined(); | ||
| }); | ||
| }); | ||
|
|
||
| describe('on iOS', () => { | ||
| let platformReplaceProperty: jest.ReplaceProperty<string>; | ||
|
|
||
| beforeEach(() => { | ||
| platformReplaceProperty = jest.replaceProperty(Platform, 'OS', 'ios'); | ||
| }); | ||
|
|
||
| afterEach(() => { | ||
| platformReplaceProperty.restore(); | ||
| }); | ||
|
|
||
| it('returns undefined when both sides fit within the budget', () => { | ||
| expect(getBoundedResizeForDimensions(2000, 1500)).toBeUndefined(); | ||
| }); | ||
|
|
||
| it('caps the width for an oversized landscape crop', () => { | ||
| expect(getBoundedResizeForDimensions(8000, 6000)).toEqual({width: MAX}); | ||
| }); | ||
|
|
||
| it('caps the height for an oversized portrait crop', () => { | ||
| expect(getBoundedResizeForDimensions(6000, 8000)).toEqual({height: MAX}); | ||
| }); | ||
| }); | ||
| }); |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
On iOS with oversized HEICs, this resize is queued only after
ImageManipulator.manipulate(sourceUri)has created the Expo context. Inexpo-image-manipulator@55, context creation immediately loads the source and runs the built-in orientation transformer, which allocates a full-sizeCGContextbefore any queued resize transformer executes. That means a 48MP HEIC can still hit the same full-bitmap allocation and OOM before this cap helps; the same pattern is repeated in the AttachmentPicker and crop/rotate paths. This needs a path that downscales during the native load/Photos request, or otherwise avoids ImageManipulator for the initial decode.Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
You're right, and I verified it in the expo-image-manipulator@55 source.
manipulate()always queuesImageFixOrientationTransformerbefore any user resize, and that transformer unconditionally allocates a full-sizeCGContext(width × height, RGBA) and draws the source into it — so the full-resolution bitmap is materialized before the resize runs. The resize only shrinks the output; it doesn't lower the peak, so this cap doesn't prevent the OOM on a single large decode.Given that, the effective mitigation is the sequencing PR (#94976), which bounds how many full-resolution decodes are alive at once. A true per-image cap would need a downsampling decode at load time (e.g. ImageIO
CGImageSourceCreateThumbnailAtIndexwithkCGImageSourceThumbnailMaxPixelSize+kCGImageSourceCreateThumbnailWithTransform), which ImageManipulator doesn't expose. Deferring to the team on whether to close this PR or repurpose it for a native downsample.