XNU Image Fuzzer 1.8.2
Documentation for XNU Image Fuzzer
Loading...
Searching...
No Matches
xnuimagefuzzer.m File Reference

XNU Image Fuzzer. More...

import <Foundation/Foundation.h>
import <UIKit/UIKit.h>
import <CoreGraphics/CoreGraphics.h>
import "AppDelegate.h"
import <os/log.h>
import <os/signpost.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <math.h>
#include <stdbool.h>
#include <float.h>
#include <string.h>
#include <stdint.h>
#include <sys/sysctl.h>
import <ImageIO/ImageIO.h>
import <UniformTypeIdentifiers/UniformTypeIdentifiers.h>
+ Include dependency graph for xnuimagefuzzer.m:

Go to the source code of this file.

Macros

#define ALL   -1
 Defines constants for general application configuration.
 
#define MAX_PERMUTATION   12
 
#define COMM_PAGE64_BASE_ADDRESS   (0x0000000FFFFFC000ULL)
 
#define COMM_PAGE_CPU_CAPABILITIES64   (COMM_PAGE64_BASE_ADDRESS + 0x010)
 
#define MAX_PERMUTATION   12
 
#define COMM_PAGE_VERSION   (COMM_PAGE64_BASE_ADDRESS + 0x01E)
 
#define COMM_PAGE_NCPUS   (COMM_PAGE64_BASE_ADDRESS + 0x022)
 
#define COMM_PAGE_CACHE_LINESIZE   (COMM_PAGE64_BASE_ADDRESS + 0x026)
 
#define COMM_PAGE_SCHED_GEN   (COMM_PAGE64_BASE_ADDRESS + 0x028)
 
#define COMM_PAGE_MEMORY_PRESSURE   (COMM_PAGE64_BASE_ADDRESS + 0x02c)
 
#define COMM_PAGE_SPIN_COUNT   (COMM_PAGE64_BASE_ADDRESS + 0x030)
 
#define COMM_PAGE_KDEBUG_ENABLE   (COMM_PAGE64_BASE_ADDRESS + 0x044)
 
#define COMM_PAGE_ATM_DIAGNOSTIC_CONFIG   (COMM_PAGE64_BASE_ADDRESS + 0x048)
 
#define COMM_PAGE_BOOTTIME_USEC   (COMM_PAGE64_BASE_ADDRESS + 0x0C8)
 
#define COMM_PAGE_ACTIVE_CPUS   (COMM_PAGE64_BASE_ADDRESS + 0x034)
 
#define COMM_PAGE_PHYSICAL_CPUS   (COMM_PAGE64_BASE_ADDRESS + 0x035)
 
#define COMM_PAGE_LOGICAL_CPUS   (COMM_PAGE64_BASE_ADDRESS + 0x036)
 
#define COMM_PAGE_MEMORY_SIZE   (COMM_PAGE64_BASE_ADDRESS + 0x038)
 
#define COMM_PAGE_CPUFAMILY   (COMM_PAGE64_BASE_ADDRESS + 0x040)
 
#define COMM_PAGE_CPU_CAPABILITIES64   (COMM_PAGE64_BASE_ADDRESS + 0x010)
 
#define _XOPEN_SOURCE
 Provides ANSI color codes for enhancing console output readability.
 
#define MAG(string)   "\x1b[0;35m" string RESET_COLOR
 
#define BLUE(string)   "\x1b[34m" string RESET_COLOR
 
#define RED(string)   "\x1b[31m" string RESET_COLOR
 
#define WHT(string)   "\x1b[0;37m" string RESET_COLOR
 
#define GRN(string)   "\x1b[0;32m" string RESET_COLOR
 
#define YEL(string)   "\x1b[0;33m" string RESET_COLOR
 
#define CYN(string)   "\x1b[0;36m" string RESET_COLOR
 
#define HWHT(string)   "\x1b[0;97m" string RESET_COLOR
 
#define NORMAL_COLOR(string)   "\x1B[0m" string RESET_COLOR
 
#define RESET_COLOR   "\x1b[0m"
 
#define INJECT_STRING_1   "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
 Configures robust strings for security testing within the application.
 
#define INJECT_STRING_2   "<script>console.error('XNU Image Fuzzer');</script>"
 
#define INJECT_STRING_3   "' OR ''='"
 
#define INJECT_STRING_4   "%d %s %d %s"
 
#define INJECT_STRING_5   "XNU Image Fuzzer"
 
#define INJECT_STRING_6   "123456; DROP TABLE users"
 
#define INJECT_STRING_7   "!@#$%^&*()_+="
 
#define INJECT_STRING_8   "..//..//..//win"
 
#define INJECT_STRING_9   "\0\0\0"
 
#define INJECT_STRING_10   "<?xml version=\"1.0\"?><!DOCTYPE replace [<!ENTITY example \"XNUImageFuzzer\"> ]><userInfo><firstName>XNUImageFuzzer<&example;></firstName></userInfo>"
 
#define NUMBER_OF_STRINGS   10
 
#define DebugLog(...)
 Provides macros for enhanced logging and assertions during development.
 
#define AssertWithMessage(condition, message, ...)
 
#define READ_COMM_PAGE_VALUE(type, address)   (*((type *)(address)))
 Dumps key communication page details for diagnostic purposes.
 

Functions

NSString * formattedCurrentDateTime (void)
 
char * signature (void)
 
void dumpDeviceInfo (void)
 Logs comprehensive information about the current device.
 
void dumpMacDeviceInfo (void)
 Logs system information for macOS devices.
 
void dump_comm_page (void)
 
void printColored (const char *color, const char *message)
 Prints a message with specified ANSI color to the console.
 
BOOL isValidImagePath (NSString *path)
 Prototypes for utility functions used in image processing.
 
unsigned long hashString (const char *str)
 Computes a hash value for a given string.
 
UIImage * loadImageFromFile (NSString *imageName)
 Loads an image from the application bundle into a UIImage object.
 
NSData * UIImageGIFRepresentation (UIImage *image)
 Creates a GIF representation of a UIImage. This custom function handles the conversion of a UIImage to GIF data using the Image I/O framework.
 
NSData * generateFuzzedImageData (size_t width, size_t height, CFStringRef imageType)
 Generates a random image for fuzzing.
 
void processImage (UIImage *image, int permutation)
 Processes an image using various bitmap context configurations.
 
void addAdditiveNoise (float *pixel)
 
void applyMultiplicativeNoise (float *pixel)
 
void invertColor (float *pixel)
 
void applyExtremeValues (float *pixel)
 
void assignSpecialFloatValues (float *pixel)
 
void applyColorShift (unsigned char *data, size_t index)
 Applies a color shift to a specific pixel within the image data.
 
void applyPixelScramble (unsigned char *data, size_t index)
 Randomly scrambles the RGB values of a pixel.
 
void createBitmapContextStandardRGB (CGImageRef cgImg, int permutation)
 Creates a bitmap context with standard RGB settings, applies a fuzzing process to alter the image, and saves the fuzzed image. Useful for testing image processing functionalities or creating varied visual effects.
 
void createBitmapContextPremultipliedFirstAlpha (CGImageRef cgImg)
 Creates a bitmap context with Premultiplied First Alpha settings and applies image processing.
 
void createBitmapContextNonPremultipliedAlpha (CGImageRef cgImg)
 Creates a bitmap graphics context with Non-Premultiplied Alpha settings for processing a CGImage.
 
void createBitmapContext16BitDepth (CGImageRef cgImg)
 Creates a bitmap graphics context for 16-bit depth per channel processing.
 
void createBitmapContextGrayscale (CGImageRef cgImg)
 
void createBitmapContextHDRFloatComponents (CGImageRef cgImg)
 Initializes a bitmap context for HDR content with floating-point components.
 
void createBitmapContextAlphaOnly (CGImageRef cgImg)
 Creates a bitmap context for alpha channel manipulation of a CGImageRef.
 
void createBitmapContext1BitMonochrome (CGImageRef cgImg)
 Creates a bitmap context for 1-bit monochrome image processing.
 
void createBitmapContextBigEndian (CGImageRef cgImg)
 Creates a bitmap context with Big Endian byte ordering for image data processing.
 
void createBitmapContextLittleEndian (CGImageRef cgImg)
 Initializes a bitmap context with Little Endian settings for image data processing.
 
void createBitmapContext8BitInvertedColors (CGImageRef cgImg)
 Transforms the color representation of an image by inverting its colors and applying an 8-bit color depth.
 
void createBitmapContext32BitFloat4Component (CGImageRef cgImg)
 Creates a bitmap context with standard RGB settings, applies a fuzzing process to alter the image, and saves the fuzzed image. Useful for testing image processing functionalities or creating varied visual effects.
 
void applyFuzzingToBitmapContext (unsigned char *rawData, size_t width, size_t height)
 Applies fuzzing to the RGB components of each pixel in a bitmap context.
 
void applyEnhancedFuzzingToBitmapContext (unsigned char *rawData, size_t width, size_t height, BOOL verboseLogging)
 Applies enhanced fuzzing techniques to bitmap data.
 
void logPixelData (unsigned char *rawData, size_t width, size_t height, const char *message, BOOL verboseLogging)
 Logs information about a random set of pixels from an image's raw data.
 
void convertTo1BitMonochrome (unsigned char *rawData, size_t width, size_t height)
 Converts image data to 1-bit monochrome using a simple thresholding technique.
 
void saveMonochromeImage (UIImage *image, NSString *identifier)
 Saves a monochrome UIImage with a specified identifier to the documents directory.
 
void saveFuzzedImage (UIImage *image, NSString *contextDescription)
 Saves a modified (fuzzed) UIImage to the documents directory.
 
NSString * createUniqueDirectoryForSavingImages (void)
 Creates a unique directory for saving images within the documents directory.
 
void LogRandomPixelData (unsigned char *rawData, size_t width, size_t height, const char *message)
 Logs information about a random set of pixels from an image's raw data.
 
void applyEnhancedFuzzingToBitmapContextWithFloats (float *rawData, size_t width, size_t height, BOOL verboseLogging)
 Applies enhanced fuzzing techniques to bitmap data using 32-bit floating-point precision.
 
void applyEnhancedFuzzingToBitmapContextAlphaOnly (unsigned char *alphaData, size_t width, size_t height, BOOL verboseLogging)
 Applies enhanced fuzzing techniques to the alpha channel of bitmap pixel data.
 
void debugMemoryHandling (void)
 Allocates and deallocates memory chunks using mmap and munmap for debugging.
 
void performAllImagePermutations (void)
 Generates a random image and processes it with all permutation strategies.
 
int main (int argc, const char *argv[])
 Entry point of the application, handling initialization, argument parsing, and image processing.
 

Variables

static int verboseLogging = 0
 Core and external libraries necessary for the fuzzer functionality.
 
char * injectStrings [10]
 
const char * cpu_cap_strings []
 Identifies the CPU's supported capabilities.
 

Detailed Description

XNU Image Fuzzer.

Author
David Hoyt
Date
01 JUN 2024
Version
1.8.1

This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/.

CHANGES

  • 26/11/2023, h02332: Initial commit
  • 21/02/2024, h02332: Refactor Programming Mistakes
  • 21/02/2024, h02332: PermaLink https://srd.cx/xnu-image-fuzzer/
  • 01/06/2024, h02332: Syntax Changes for Documentation Tools

ROADMAP

  • Grayscale Implementation
  • ICC Color Profiles.

Definition in file xnuimagefuzzer.m.

Macro Definition Documentation

◆ _XOPEN_SOURCE

#define _XOPEN_SOURCE

Provides ANSI color codes for enhancing console output readability.

Use these definitions to add color to console logs, improving the distinction between different types of messages. Each macro wraps a given string with the ANSI code for a specific color and automatically resets the color to default after the string. This ensures that only the intended text is colored, without affecting subsequent console output.

Example Usage:

NSLog(@"%@", RED("Error: Invalid input"));
NSLog(@"%@", GRN("Operation completed successfully"));
#define RED(string)
#define GRN(string)
Note
The effectiveness and appearance of these color codes can vary based on the terminal or console application used. Ensure your development and deployment environments support ANSI color codes.

Definition at line 143 of file xnuimagefuzzer.m.

◆ ALL

#define ALL   -1

Defines constants for general application configuration.

This section includes definitions for constants used throughout the application to control its behavior and configuration. These constants are pivotal for ensuring the application operates within defined parameters and accesses system resources correctly.

  • ALL: A special flag used to indicate an operation applies to all items or states. Useful for functions that require a broad application of their logic.
  • MAX_PERMUTATION: Defines the upper limit on the number of permutations that can be applied in image processing tasks. This constant helps in preventing excessive processing time and resource consumption.
  • COMM_PAGE64_BASE_ADDRESS: The base memory address for the comm page, which is a reserved area of memory used by the system to store variables that are accessed frequently.
  • COMM_PAGE_CPU_CAPABILITIES64: An offset from COMM_PAGE64_BASE_ADDRESS that points to the CPU capabilities. Useful for quickly determining the hardware capabilities of the system.

Example Usage:

if (operationMode == ALL) {
// Apply operation to all items
}
int permutations = MAX_PERMUTATION;
uint64_t commPageAddress = COMM_PAGE64_BASE_ADDRESS;
uint64_t cpuCapabilitiesAddress = COMM_PAGE_CPU_CAPABILITIES64;
#define ALL
Defines constants for general application configuration.
#define COMM_PAGE_CPU_CAPABILITIES64
#define MAX_PERMUTATION
#define COMM_PAGE64_BASE_ADDRESS
Note
These constants are designed to be used across various components of the application, providing a centralized point of reference for important values and system parameters.

Definition at line 89 of file xnuimagefuzzer.m.

◆ AssertWithMessage

#define AssertWithMessage ( condition,
message,
... )
Value:
do { \
if (!(condition)) { \
NSLog((@"Assertion failed: %s " message), #condition, ##__VA_ARGS__); \
assert(condition); \
} \
} while(0)
Examples
Usage.

Definition at line 243 of file xnuimagefuzzer.m.

243#define AssertWithMessage(condition, message, ...) \
244 do { \
245 if (!(condition)) { \
246 NSLog((@"Assertion failed: %s " message), #condition, ##__VA_ARGS__); \
247 assert(condition); \
248 } \
249 } while(0)

◆ BLUE

#define BLUE ( string)    "\x1b[34m" string RESET_COLOR

Definition at line 145 of file xnuimagefuzzer.m.

◆ COMM_PAGE64_BASE_ADDRESS

#define COMM_PAGE64_BASE_ADDRESS   (0x0000000FFFFFC000ULL)

Definition at line 91 of file xnuimagefuzzer.m.

Referenced by dump_comm_page(), and signature().

◆ COMM_PAGE_ACTIVE_CPUS

#define COMM_PAGE_ACTIVE_CPUS   (COMM_PAGE64_BASE_ADDRESS + 0x034)

Definition at line 110 of file xnuimagefuzzer.m.

◆ COMM_PAGE_ATM_DIAGNOSTIC_CONFIG

#define COMM_PAGE_ATM_DIAGNOSTIC_CONFIG   (COMM_PAGE64_BASE_ADDRESS + 0x048)

Definition at line 108 of file xnuimagefuzzer.m.

◆ COMM_PAGE_BOOTTIME_USEC

#define COMM_PAGE_BOOTTIME_USEC   (COMM_PAGE64_BASE_ADDRESS + 0x0C8)

Definition at line 109 of file xnuimagefuzzer.m.

◆ COMM_PAGE_CACHE_LINESIZE

#define COMM_PAGE_CACHE_LINESIZE   (COMM_PAGE64_BASE_ADDRESS + 0x026)

Definition at line 103 of file xnuimagefuzzer.m.

◆ COMM_PAGE_CPU_CAPABILITIES64 [1/2]

#define COMM_PAGE_CPU_CAPABILITIES64   (COMM_PAGE64_BASE_ADDRESS + 0x010)

Definition at line 92 of file xnuimagefuzzer.m.

Referenced by dump_comm_page().

◆ COMM_PAGE_CPU_CAPABILITIES64 [2/2]

#define COMM_PAGE_CPU_CAPABILITIES64   (COMM_PAGE64_BASE_ADDRESS + 0x010)

Definition at line 92 of file xnuimagefuzzer.m.

◆ COMM_PAGE_CPUFAMILY

#define COMM_PAGE_CPUFAMILY   (COMM_PAGE64_BASE_ADDRESS + 0x040)

Definition at line 114 of file xnuimagefuzzer.m.

◆ COMM_PAGE_KDEBUG_ENABLE

#define COMM_PAGE_KDEBUG_ENABLE   (COMM_PAGE64_BASE_ADDRESS + 0x044)

Definition at line 107 of file xnuimagefuzzer.m.

◆ COMM_PAGE_LOGICAL_CPUS

#define COMM_PAGE_LOGICAL_CPUS   (COMM_PAGE64_BASE_ADDRESS + 0x036)

Definition at line 112 of file xnuimagefuzzer.m.

◆ COMM_PAGE_MEMORY_PRESSURE

#define COMM_PAGE_MEMORY_PRESSURE   (COMM_PAGE64_BASE_ADDRESS + 0x02c)

Definition at line 105 of file xnuimagefuzzer.m.

◆ COMM_PAGE_MEMORY_SIZE

#define COMM_PAGE_MEMORY_SIZE   (COMM_PAGE64_BASE_ADDRESS + 0x038)

Definition at line 113 of file xnuimagefuzzer.m.

◆ COMM_PAGE_NCPUS

#define COMM_PAGE_NCPUS   (COMM_PAGE64_BASE_ADDRESS + 0x022)

Definition at line 102 of file xnuimagefuzzer.m.

◆ COMM_PAGE_PHYSICAL_CPUS

#define COMM_PAGE_PHYSICAL_CPUS   (COMM_PAGE64_BASE_ADDRESS + 0x035)

Definition at line 111 of file xnuimagefuzzer.m.

◆ COMM_PAGE_SCHED_GEN

#define COMM_PAGE_SCHED_GEN   (COMM_PAGE64_BASE_ADDRESS + 0x028)

Definition at line 104 of file xnuimagefuzzer.m.

◆ COMM_PAGE_SPIN_COUNT

#define COMM_PAGE_SPIN_COUNT   (COMM_PAGE64_BASE_ADDRESS + 0x030)

Definition at line 106 of file xnuimagefuzzer.m.

◆ COMM_PAGE_VERSION

#define COMM_PAGE_VERSION   (COMM_PAGE64_BASE_ADDRESS + 0x01E)

Definition at line 101 of file xnuimagefuzzer.m.

◆ CYN

#define CYN ( string)    "\x1b[0;36m" string RESET_COLOR

Definition at line 150 of file xnuimagefuzzer.m.

◆ DebugLog

#define DebugLog ( ...)

Provides macros for enhanced logging and assertions during development.

This section defines two key macros designed to assist in the debugging process, ensuring that developers can log detailed information and perform assertions with customized messages. These macros are especially useful in DEBUG builds, where additional context can significantly aid in diagnosing issues.

Features:

  • DebugLog: This macro is used for logging detailed debug information, including the name of the current function and the line number from where it's called. It's instrumental in tracing the execution flow or pinpointing the location of specific events or states in the code.
  • AssertWithMessage: This macro allows for the execution of assertions that, upon failure, log a custom message. It's valuable for validating assumptions within the code and providing immediate feedback if those assumptions are violated.

Usage:

DebugLog

Use the DebugLog macro to log messages with additional context, such as the function name and line number. This macro is only active in DEBUG builds, helping to avoid the potential exposure of sensitive information in release builds.

DebugLog(@"An informative debug message with context.");
#define DebugLog(...)
Provides macros for enhanced logging and assertions during development.

Definition at line 226 of file xnuimagefuzzer.m.

◆ GRN

#define GRN ( string)    "\x1b[0;32m" string RESET_COLOR

Definition at line 148 of file xnuimagefuzzer.m.

◆ HWHT

#define HWHT ( string)    "\x1b[0;97m" string RESET_COLOR

Definition at line 151 of file xnuimagefuzzer.m.

◆ INJECT_STRING_1

#define INJECT_STRING_1   "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"

Configures robust strings for security testing within the application.

These strings are tailored to simulate a variety of inputs aimed at testing the application's resilience against common and uncommon vulnerabilities. They include tests for SQL injections, XSS, buffer overflows, and more.

  • INJECT_STRING_1 to INJECT_STRING_10: Each string targets different aspects of security handling, from special character processing to injection attacks.

NUMBER_OF_STRINGS: Denotes the total number of defined injection strings, aiding in their application across varied test scenarios.

Example Usage:

for (int i = 0; i < NUMBER_OF_STRINGS; i++) {
testFunctionWithInjectionString(INJECT_STRINGS[i]);
}
#define NUMBER_OF_STRINGS
Note
Use these strings in a controlled environment to ensure they help identify potential security flaws without causing unintended harm.

Definition at line 177 of file xnuimagefuzzer.m.

◆ INJECT_STRING_10

#define INJECT_STRING_10   "<?xml version=\"1.0\"?><!DOCTYPE replace [<!ENTITY example \"XNUImageFuzzer\"> ]><userInfo><firstName>XNUImageFuzzer<&example;></firstName></userInfo>"

Definition at line 186 of file xnuimagefuzzer.m.

◆ INJECT_STRING_2

#define INJECT_STRING_2   "<script>console.error('XNU Image Fuzzer');</script>"

Definition at line 178 of file xnuimagefuzzer.m.

◆ INJECT_STRING_3

#define INJECT_STRING_3   "' OR ''='"

Definition at line 179 of file xnuimagefuzzer.m.

◆ INJECT_STRING_4

#define INJECT_STRING_4   "%d %s %d %s"

Definition at line 180 of file xnuimagefuzzer.m.

◆ INJECT_STRING_5

#define INJECT_STRING_5   "XNU Image Fuzzer"

Definition at line 181 of file xnuimagefuzzer.m.

◆ INJECT_STRING_6

#define INJECT_STRING_6   "123456; DROP TABLE users"

Definition at line 182 of file xnuimagefuzzer.m.

◆ INJECT_STRING_7

#define INJECT_STRING_7   "!@#$%^&*()_+="

Definition at line 183 of file xnuimagefuzzer.m.

◆ INJECT_STRING_8

#define INJECT_STRING_8   "..//..//..//win"

Definition at line 184 of file xnuimagefuzzer.m.

◆ INJECT_STRING_9

#define INJECT_STRING_9   "\0\0\0"

Definition at line 185 of file xnuimagefuzzer.m.

◆ MAG

#define MAG ( string)    "\x1b[0;35m" string RESET_COLOR

Definition at line 144 of file xnuimagefuzzer.m.

◆ MAX_PERMUTATION [1/2]

#define MAX_PERMUTATION   12

Definition at line 90 of file xnuimagefuzzer.m.

◆ MAX_PERMUTATION [2/2]

#define MAX_PERMUTATION   12

Definition at line 90 of file xnuimagefuzzer.m.

◆ NORMAL_COLOR

#define NORMAL_COLOR ( string)    "\x1B[0m" string RESET_COLOR

Definition at line 152 of file xnuimagefuzzer.m.

◆ NUMBER_OF_STRINGS

◆ READ_COMM_PAGE_VALUE

#define READ_COMM_PAGE_VALUE ( type,
address )   (*((type *)(address)))

Dumps key communication page details for diagnostic purposes.

This function extracts and logs essential details from the system's communication page, such as the signature, version, and number of CPUs, along with CPU capabilities. It utilizes the READ_COMM_PAGE_VALUE macro to read values directly from specified memory addresses, facilitating a low-level inspection of system configurations and capabilities.

Behavior:

  1. Retrieves and logs the communication page signature. If the signature cannot be read, logs an error message.
  2. Logs the communication page version and number of CPU cores by reading from predefined offsets within the communication page.
  3. Enumerates and logs CPU capabilities based on the COMM_PAGE_CPU_CAPABILITIES64 address. Each capability is checked and logged, indicating whether it is supported.

Parameters:

This function does not take any parameters.

Return:

This function does not return a value.

Example Output:

  • [*] COMM_PAGE_SIGNATURE: <signature_value> or [*] COMM_PAGE_SIGNATURE: Error reading signature.
  • [*] COMM_PAGE_VERSION: <version_number>
  • [*] COMM_PAGE_NCPUS: <cpu_count>
  • Lists CPU capabilities as true/false based on the current system's hardware configuration.

Note:

  • The actual information logged will depend on the specific system and its configuration.
  • The READ_COMM_PAGE_VALUE macro is crucial for the function's operation, casting the specified address to the appropriate type before dereferencing.

See Also:

  • READ_COMM_PAGE_VALUE macro for how memory addresses are read.
  • System documentation for the communication page structure and definitions.

Usage:

dump_comm_page(); // Logs the communication page details for the current system.
void dump_comm_page(void)

Definition at line 500 of file xnuimagefuzzer.m.

Referenced by dump_comm_page().

◆ RED

#define RED ( string)    "\x1b[31m" string RESET_COLOR

Definition at line 146 of file xnuimagefuzzer.m.

◆ RESET_COLOR

#define RESET_COLOR   "\x1b[0m"

Definition at line 153 of file xnuimagefuzzer.m.

Referenced by printColored().

◆ WHT

#define WHT ( string)    "\x1b[0;37m" string RESET_COLOR

Definition at line 147 of file xnuimagefuzzer.m.

◆ YEL

#define YEL ( string)    "\x1b[0;33m" string RESET_COLOR

Definition at line 149 of file xnuimagefuzzer.m.

Function Documentation

◆ addAdditiveNoise()

void addAdditiveNoise ( float * pixel)

◆ applyColorShift()

void applyColorShift ( unsigned char * data,
size_t index )

Applies a color shift to a specific pixel within the image data.

This method modifies the RGB values of the specified pixel by randomly increasing or decreasing these values, which can simulate color distortion effects useful in fuzzing tests.

Parameters
dataThe raw image data array.
indexThe index of the pixel within the data array where the color shift will be applied.

Definition at line 942 of file xnuimagefuzzer.m.

942 {
943 for (int i = 0; i < 3; i++) { // Affecting RGB channels
944 int shift = (arc4random_uniform(2) == 0) ? -15 : 15; // Randomly decide to increase or decrease color value
945 int newValue = data[index + i] + shift;
946 data[index + i] = (unsigned char)fmax(0, fmin(255, newValue)); // Ensure the new value is within the byte range
947 }
948}

Referenced by applyEnhancedFuzzingToBitmapContext().

+ Here is the caller graph for this function:

◆ applyEnhancedFuzzingToBitmapContext()

void applyEnhancedFuzzingToBitmapContext ( unsigned char * rawData,
size_t width,
size_t height,
BOOL verboseLogging )

Applies enhanced fuzzing techniques to bitmap data.

This function targets the robustness of image processing routines by applying a comprehensive set of fuzzing techniques directly to the raw pixel data of a bitmap. Techniques include string injections to simulate security testing scenarios, visual distortions such as inversion, noise addition, random color adjustments, pixel value shifts, contrast modifications, and color swapping under predefined conditions. The goal is to simulate a variety of real-world inputs, both benign and malicious, thereby uncovering potential vulnerabilities and ensuring the image processing system can handle unexpected inputs gracefully.

Parameters
rawDataPointer to the raw pixel data of the bitmap, which is modified in place. This data should be in RGBA format, where each pixel is represented by four bytes for red, green, blue, and alpha components.
widthThe width of the bitmap in pixels, used to navigate the pixel data array.
heightThe height of the bitmap in pixels, indicating the total number of pixel rows in the rawData.
verboseLoggingIf enabled (true), the function logs detailed information about each fuzzing action and its effect on the pixel data, facilitating debugging and providing insights into the impact of different fuzzing techniques on the bitmap.
Note
The rawData buffer is expected to accommodate width * height pixels, each represented by 4 bytes. The function directly modifies this buffer, reflecting the applied fuzzing techniques without returning any value. It serves as a critical tool for enhancing the security and robustness of image processing algorithms by exposing them to a broad spectrum of test conditions.

Definition at line 980 of file xnuimagefuzzer.m.

980 {
981 if (!rawData || width == 0 || height == 0) {
982 NSLog(@"No valid raw data or dimensions available for enhanced fuzzing.");
983 return;
984 }
985
986 size_t stringIndex = 0;
987 size_t injectIndex = 0;
988 size_t totalStringsInjected = 0;
989 const size_t numFuzzMethods = 8; // Increased number of fuzz methods
990
991 if (verboseLogging) {
992 NSLog(@"Starting enhanced fuzzing on bitmap context");
993 }
994
995 for (size_t y = 0; y < height; y++) {
996 for (size_t x = 0; x < width; x++) {
997 size_t pixelIndex = (y * width + x) * 4; // Assuming RGBA format
998 int fuzzMethod = arc4random_uniform(numFuzzMethods); // Now selecting from eight methods
999
1000 if (totalStringsInjected < NUMBER_OF_STRINGS) {
1001 if (injectIndex == 0 && verboseLogging) {
1002 NSLog(@"Starting injection of string %zu: %s", stringIndex + 1, injectStrings[stringIndex]);
1003 }
1004
1005 char *currentString = injectStrings[stringIndex];
1006 size_t stringLength = strlen(currentString);
1007
1008 if (injectIndex < stringLength) {
1009 // Encode a character into both the MSB and LSB of the pixel data
1010 for (int i = 0; i < 3; i++) { // Affecting RGB channels
1011 // Encoding into the Least Significant Bit
1012 rawData[pixelIndex + i] &= 0xFE; // Clear the least significant bit
1013 rawData[pixelIndex + i] |= (currentString[injectIndex] & 0x01); // Set the least significant bit
1014
1015 // Encoding into the Most Significant Bit
1016 rawData[pixelIndex + i] &= 0x7F; // Clear the most significant bit
1017 rawData[pixelIndex + i] |= (currentString[injectIndex] & 0x80); // Set the most significant bit if needed
1018 }
1019 injectIndex++;
1020 }
1021
1022 if (injectIndex == stringLength) {
1023 if (verboseLogging) {
1024 NSLog(@"Completed injection of string %zu: %s", stringIndex + 1, currentString);
1025 }
1026 injectIndex = 0; // Reset the injection index for the next string
1027 stringIndex = (stringIndex + 1) % NUMBER_OF_STRINGS; // Cycle through strings
1028 totalStringsInjected++;
1029 }
1030 }
1031
1032
1033 switch (fuzzMethod) {
1034 case 0: // Inversion
1035 if (verboseLogging) {
1036 NSLog(@"Inversion applied at Pixel[%zu, %zu]", x, y);
1037 }
1038 for (int i = 0; i < 3; i++) { // Apply inversion to RGB
1039 rawData[pixelIndex + i] = 255 - rawData[pixelIndex + i];
1040 }
1041 break;
1042 case 1: // Random noise
1043 if (verboseLogging) {
1044 NSLog(@"Random noise applied at Pixel[%zu, %zu]", x, y);
1045 }
1046 for (int i = 0; i < 4; i++) { // Including alpha channel
1047 int noise = (arc4random_uniform(101) - 50); // Noise range [-50, 50]
1048 int newValue = rawData[pixelIndex + i] + noise;
1049 rawData[pixelIndex + i] = (unsigned char)fmax(0, fmin(255, newValue));
1050 }
1051 break;
1052 case 2: // Random color
1053 if (verboseLogging) {
1054 NSLog(@"Random color set at Pixel[%zu, %zu]", x, y);
1055 }
1056 // Assign random colors to RGB, leaving alpha unchanged
1057 for (int i = 0; i < 3; i++) {
1058 rawData[pixelIndex + i] = arc4random_uniform(256);
1059 }
1060 break;
1061 case 3: // Shift pixel values
1062 if (verboseLogging) {
1063 NSLog(@"Shift pixel values applied at Pixel[%zu, %zu]", x, y);
1064 }
1065 // Circular shift right for RGB values
1066 unsigned char temp = rawData[pixelIndex + 2]; // Temporarily store the Blue value
1067 rawData[pixelIndex + 2] = rawData[pixelIndex + 1]; // Move Green to Blue
1068 rawData[pixelIndex + 1] = rawData[pixelIndex]; // Move Red to Green
1069 rawData[pixelIndex] = temp; // Move original Blue to Red
1070 break;
1071 case 4: // Extreme contrast adjustment
1072 if (verboseLogging) {
1073 NSLog(@"Extreme contrast adjustment at Pixel[%zu, %zu]", x, y);
1074 }
1075 for (int i = 0; i < 3; i++) {
1076 rawData[pixelIndex + i] = rawData[pixelIndex + i] < 128 ? 0 : 255;
1077 }
1078 break;
1079 case 5: // Conditional color swap
1080 if (verboseLogging) {
1081 NSLog(@"Conditional color swap at Pixel[%zu, %zu]", x, y);
1082 }
1083 // Swap Red and Blue based on a simple condition
1084 if ((x + y) % 2 == 0) {
1085 unsigned char temp = rawData[pixelIndex];
1086 rawData[pixelIndex] = rawData[pixelIndex + 2];
1087 rawData[pixelIndex + 2] = temp;
1088 }
1089 break;
1090 case 6:
1091 applyColorShift(rawData, pixelIndex);
1092 if (verboseLogging) {
1093 NSLog(@"Color Shift applied at Pixel[%zu, %zu]", x, y);
1094 }
1095 break;
1096 case 7:
1097 applyPixelScramble(rawData, pixelIndex);
1098 if (verboseLogging) {
1099 NSLog(@"Pixel Scramble applied at Pixel[%zu, %zu]", x, y);
1100 }
1101 break;
1102 }
1103 }
1104 }
1105
1106 if (verboseLogging) {
1107 if (totalStringsInjected == NUMBER_OF_STRINGS) {
1108 NSLog(@"Successfully injected all %zu strings.", totalStringsInjected);
1109 } else {
1110 NSLog(@"Error: Not all strings were successfully injected. Total injected: %zu", totalStringsInjected);
1111 }
1112 NSLog(@"Enhanced fuzzing on bitmap context completed.");
1113 }
1114}
void applyColorShift(unsigned char *data, size_t index)
Applies a color shift to a specific pixel within the image data.
static int verboseLogging
Core and external libraries necessary for the fuzzer functionality.
void applyPixelScramble(unsigned char *data, size_t index)
Randomly scrambles the RGB values of a pixel.
char * injectStrings[10]

References applyColorShift(), applyPixelScramble(), injectStrings, NUMBER_OF_STRINGS, and verboseLogging.

Referenced by createBitmapContext16BitDepth(), createBitmapContext8BitInvertedColors(), createBitmapContextBigEndian(), createBitmapContextLittleEndian(), createBitmapContextNonPremultipliedAlpha(), createBitmapContextPremultipliedFirstAlpha(), and createBitmapContextStandardRGB().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ applyEnhancedFuzzingToBitmapContextAlphaOnly()

void applyEnhancedFuzzingToBitmapContextAlphaOnly ( unsigned char * alphaData,
size_t width,
size_t height,
BOOL verboseLogging )

Applies enhanced fuzzing techniques to the alpha channel of bitmap pixel data.

This function focuses on testing and improving the resilience of image processing routines to handle unusual or extreme alpha values effectively. By manipulating the alpha transparency data in various ways, it simulates edge cases or malicious inputs that could occur in real-world applications. The function employs several fuzzing methods, including alpha inversion, setting random transparency extremes, and introducing noise, to challenge and enhance the robustness of image processing algorithms.

Parameters
alphaDataPointer to the alpha channel data of the bitmap context. This buffer contains only the alpha (transparency) values for each pixel, represented by one byte per pixel.
widthThe width of the bitmap in pixels, defining the row length in the alpha data array.
heightThe height of the bitmap in pixels, indicating the total number of rows in the alpha data.
verboseLoggingWhen YES, enables detailed logging of each fuzzing operation and its impact on the alpha channel, aiding in debugging and analysis of the fuzzing effects.
Note
The function iteratively applies fuzzing techniques to each alpha value, directly modifying the alphaData buffer to reflect these changes. It includes initial validity checks to ensure that operations are conducted on valid data with positive dimensions, and logs a message before aborting if parameters are found to be invalid. The goal is to ensure that image processing systems are capable of handling a wide range of transparency variations, thereby enhancing both the visual quality and security of applications that rely on such routines.

Definition at line 1223 of file xnuimagefuzzer.m.

1223 {
1224 if (!alphaData || width == 0 || height == 0) {
1225 NSLog(@"No valid alpha data or dimensions available for enhanced fuzzing.");
1226 return;
1227 }
1228
1229 if (verboseLogging) {
1230 NSLog(@"Starting enhanced fuzzing on Alpha-only bitmap context");
1231 }
1232
1233 for (size_t y = 0; y < height; y++) {
1234 for (size_t x = 0; x < width; x++) {
1235 size_t pixelIndex = y * width + x; // Direct index as we're dealing with 1 byte per pixel
1236
1237 // Randomly decide on a fuzzing method
1238 switch (arc4random_uniform(3)) { // Example with 3 simple fuzzing methods
1239 case 0: // Invert alpha value
1240 alphaData[pixelIndex] = 255 - alphaData[pixelIndex];
1241 break;
1242 case 1: // Set to fully transparent or fully opaque
1243 if (arc4random_uniform(2) == 0) {
1244 alphaData[pixelIndex] = 0; // Fully transparent
1245 } else {
1246 alphaData[pixelIndex] = 255; // Fully opaque
1247 }
1248 break;
1249 case 2: // Apply random noise
1250 {
1251 int noise = (arc4random_uniform(51)) - 25; // Random noise between -25 and 25
1252 int newAlpha = (int)alphaData[pixelIndex] + noise;
1253 alphaData[pixelIndex] = (unsigned char)fmax(0, fmin(255, newAlpha)); // Clamp between 0 and 255
1254 }
1255 break;
1256 }
1257 }
1258 }
1259
1260 if (verboseLogging) {
1261 NSLog(@"Enhanced fuzzing on Alpha-only bitmap context completed");
1262 }
1263}

References verboseLogging.

Referenced by createBitmapContextAlphaOnly().

+ Here is the caller graph for this function:

◆ applyEnhancedFuzzingToBitmapContextWithFloats()

void applyEnhancedFuzzingToBitmapContextWithFloats ( float * rawData,
size_t width,
size_t height,
BOOL verboseLogging )

Applies enhanced fuzzing techniques to bitmap data using 32-bit floating-point precision.

This function is designed to test the robustness of image processing algorithms by applying a variety of fuzzing techniques to the raw pixel data of a bitmap. It iterates through a predefined set of strings, each dictating a specific fuzzing method based on its hash value. Techniques include additive and multiplicative noise, color inversion, setting extreme values, and applying special floating-point values such as NaN or Infinity. The function aims to uncover potential vulnerabilities by simulating real-world inputs and ensuring that the image processing system can gracefully handle unexpected or malicious inputs.

Parameters
rawDataPointer to the raw pixel data of the bitmap, which is modified in place. The data is assumed to be in RGBA format, with each pixel represented by four 32-bit floating-point values for red, green, blue, and alpha components.
widthThe width of the bitmap in pixels, used to calculate the location of each pixel in the rawData array.
heightThe height of the bitmap in pixels, used along with the width to navigate through the rawData array.
verboseLoggingA boolean value that, when set to YES, enables detailed logging of each fuzzing action and its effects on the pixel data. This facilitates debugging and provides insights into how different fuzzing techniques impact the bitmap.
Note
The function modifies the rawData buffer in place, reflecting the applied fuzzing techniques. The buffer is expected to accommodate width * height pixels, with each pixel's data represented by four 32-bit floating-point values. It is a critical tool for enhancing the security and robustness of image processing algorithms by exposing them to a broad spectrum of test conditions.

Example usage:

float *rawData = ...; // Assume this is already allocated and populated with image data
size_t width = ...; // The width of the image
size_t height = ...; // The height of the image
BOOL verboseLogging = YES; // Enable detailed logging
void applyEnhancedFuzzingToBitmapContextWithFloats(float *rawData, size_t width, size_t height, BOOL verboseLogging)
Applies enhanced fuzzing techniques to bitmap data using 32-bit floating-point precision.

Definition at line 1139 of file xnuimagefuzzer.m.

1139 {
1140 if (!rawData || width == 0 || height == 0) {
1141 NSLog(@"Invalid parameters for enhanced fuzzing.");
1142 return;
1143 }
1144
1145 for (int stringIndex = 0; stringIndex < NUMBER_OF_STRINGS; stringIndex++) {
1146 // Log the start of fuzzing with the specific injection string
1147 if (verboseLogging) {
1148 NSLog(@"Starting enhanced fuzzing with injection string %d: %s", stringIndex + 1, injectStrings[stringIndex]);
1149 }
1150
1151 // Hash the selected injection string to determine the fuzzing method
1152 unsigned long hash = hashString(injectStrings[stringIndex]) % 5; // Modulo by 5 to fit our method range
1153
1154 for (size_t y = 0; y < height; y++) {
1155 for (size_t x = 0; x < width; x++) {
1156 size_t pixelIndex = (y * width + x) * 4; // Assuming RGBA format
1157
1158 // Apply fuzzing based on hash of injection string
1159 switch (hash) {
1160 case 0:
1161 // Additive noise
1162 for (int i = 0; i < 4; i++) {
1163 rawData[pixelIndex + i] += ((float)arc4random_uniform(6) / RAND_MAX * 2.0f - 1.0f); // Noise range [-1, 1] // Noise range [-1, 1]
1164 }
1165 break;
1166 case 1:
1167 // Multiplicative noise (scale)
1168 for (int i = 0; i < 4; i++) {
1169 rawData[pixelIndex + i] *= ((float)arc4random_uniform(6) / RAND_MAX * 2.0f); // Scale range [0, 2]
1170 }
1171 break;
1172 case 2:
1173 // Inversion
1174 for (int i = 0; i < 3; i++) { // Skipping alpha for inversion
1175 rawData[pixelIndex + i] = 1.0f - rawData[pixelIndex + i];
1176 }
1177 break;
1178 case 3:
1179 // Extreme values
1180 for (int i = 0; i < 4; i++) {
1181 rawData[pixelIndex + i] = (arc4random_uniform(6) % 2) ? FLT_MAX : FLT_MIN;
1182 }
1183 break;
1184 case 4:
1185 // Special floating-point values
1186 for (int i = 0; i < 4; i++) {
1187 switch (arc4random_uniform(6) % 3) {
1188 case 0: rawData[pixelIndex + i] = NAN; break;
1189 case 1: rawData[pixelIndex + i] = INFINITY; break;
1190 case 2: rawData[pixelIndex + i] = -INFINITY; break;
1191 }
1192 }
1193 break;
1194 }
1195 }
1196 }
1197
1198 // Log completion of the fuzzing for the specific injection string
1199 if (verboseLogging) {
1200 NSLog(@"Enhanced fuzzing with injection string %d: %s completed", stringIndex + 1, injectStrings[stringIndex]);
1201 }
1202 }
1203
1204 // Final log to indicate completion of all fuzzing processes
1205 if (verboseLogging) {
1206 NSLog(@"All enhanced fuzzing processes completed.");
1207 }
1208}
unsigned long hashString(const char *str)
Computes a hash value for a given string.

References hashString(), injectStrings, NUMBER_OF_STRINGS, and verboseLogging.

Referenced by createBitmapContext32BitFloat4Component(), and createBitmapContextHDRFloatComponents().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ applyExtremeValues()

void applyExtremeValues ( float * pixel)

◆ applyFuzzingToBitmapContext()

void applyFuzzingToBitmapContext ( unsigned char * rawData,
size_t width,
size_t height )

Applies fuzzing to the RGB components of each pixel in a bitmap context.

This function introduces small, random variations to the RGB values of each pixel to test the resilience of image processing algorithms to input data variations. The fuzzing process adjusts the R, G, and B components of each pixel within a specified range, while optionally encoding additional data into the alpha channel of the first row of pixels. This method is useful for evaluating how image processing systems handle slight inconsistencies or errors in visual data.

Parameters
rawDataPointer to the bitmap's raw pixel data, modified in-place. Assumes RGBA format, with 4 bytes per pixel. RGB components are randomly adjusted, and the alpha channel of certain pixels may encode additional data.
widthThe width of the bitmap in pixels, determining the row length in the data array.
heightThe height of the bitmap in pixels, indicating the total number of rows.
Note
The function iterates over every pixel, applying a random adjustment of -25 to +25 to the RGB values, chosen to introduce noticeable yet non-drastic variations. The alpha channel is generally preserved to maintain transparency, except in the first row where specific pixels might encode data, demonstrating a technique for embedding metadata. This fuzzing aims to reveal how slight data variations affect image processing outcomes, with an optional feature for data encoding that showcases a method for preserving information through image transformations.
  • Utilizes arc4random_uniform for a uniform distribution of fuzz factors, avoiding biases.
  • Directly modifies the rawData, requiring users to back up original data if preservation is needed.
  • Maintains original transparency for most pixels, focusing visual impact on color variations only.

Definition at line 1281 of file xnuimagefuzzer.m.

1281 {
1282 NSLog(@"Beginning fuzzing operation on bitmap context.");
1283
1284 for (size_t y = 0; y < height; y++) {
1285 for (size_t x = 0; x < width; x++) {
1286 size_t pixelIndex = (y * width + x) * 4; // 4 bytes per pixel (RGBA)
1287
1288 // Fuzzing each color component (R, G, B) within the range of 0-255
1289 for (int i = 0; i < 3; i++) { // Looping over R, G, B components
1290 // Using arc4random_uniform for a more uniform distribution and to avoid modulo bias
1291 int fuzzFactor = (int)arc4random_uniform(51) - 25; // Random number between -25 and 25
1292 int newValue = rawData[pixelIndex + i] + fuzzFactor;
1293 rawData[pixelIndex + i] = (unsigned char) fmax(0, fmin(255, newValue));
1294 }
1295 // Alpha (offset + 3) is not altered
1296
1297 // Optionally, inject encoded data into the alpha channel for testing purposes
1298 if (x < NUMBER_OF_STRINGS && y == 0) { // Simple method to inject data at the start of the image
1299 rawData[pixelIndex + 3] = strlen(injectStrings[x]); // Use the length of each string as a simple data point
1300 }
1301 }
1302 }
1303
1304 NSLog(@"Fuzzing applied to RGB components of the bitmap context. Injection data encoded in the alpha channel of the first row.");
1305}

References injectStrings, and NUMBER_OF_STRINGS.

◆ applyMultiplicativeNoise()

void applyMultiplicativeNoise ( float * pixel)

◆ applyPixelScramble()

void applyPixelScramble ( unsigned char * data,
size_t index )

Randomly scrambles the RGB values of a pixel.

This method swaps the values of two RGB channels at the given pixel index, which can help in uncovering issues related to incorrect channel processing or assumptions in color models.

Parameters
dataThe raw image data.
indexThe index of the pixel where the RGB channels will be scrambled.

Definition at line 958 of file xnuimagefuzzer.m.

958 {
959 unsigned char temp;
960 int swapIndex = arc4random_uniform(3); // Choose a random channel to swap with another
961 temp = data[index + swapIndex];
962 data[index + swapIndex] = data[index + (swapIndex + 1) % 3];
963 data[index + (swapIndex + 1) % 3] = temp;
964}

Referenced by applyEnhancedFuzzingToBitmapContext().

+ Here is the caller graph for this function:

◆ assignSpecialFloatValues()

void assignSpecialFloatValues ( float * pixel)

◆ convertTo1BitMonochrome()

void convertTo1BitMonochrome ( unsigned char * rawData,
size_t width,
size_t height )

Converts image data to 1-bit monochrome using a simple thresholding technique.

This function iterates over each pixel in the input image data, applying a fixed threshold to determine if a pixel should be black or white in the resulting monochrome image. This is a basic form of binarization, suitable for simplifying images or preparing them for certain types of processing where color is not needed.

Parameters
rawDataPointer to the image data.
widthThe width of the image in pixels.
heightThe height of the image in pixels.

Example Usage:

uint8_t *rawData = ...; // Assume this is already allocated and populated with image data
size_t width = ...; // The width of the image
size_t height = ...; // The height of the image
convertTo1BitMonochrome(rawData, width, height);
void convertTo1BitMonochrome(unsigned char *rawData, size_t width, size_t height)
Converts image data to 1-bit monochrome using a simple thresholding technique.

Definition at line 759 of file xnuimagefuzzer.m.

759 {
760 size_t bytesPerRow = (width + 7) / 8; // Calculate the bytes per row for 1bpp
761 unsigned char threshold = 127; // Midpoint threshold for black/white conversion
762
763 for (size_t y = 0; y < height; y++) {
764 for (size_t x = 0; x < width; x++) {
765 size_t byteIndex = y * bytesPerRow + x / 8;
766 unsigned char pixelValue = rawData[y * width + x]; // Assuming rawData is in a format where each pixel is a byte
767 unsigned char bit = (pixelValue > threshold) ? 1 : 0; // Apply threshold
768
769 rawData[byteIndex] &= ~(1 << (7 - (x % 8))); // Clear the bit
770 rawData[byteIndex] |= (bit << (7 - (x % 8))); // Set the bit based on threshold
771 }
772 }
773}

Referenced by createBitmapContext1BitMonochrome().

+ Here is the caller graph for this function:

◆ createBitmapContext16BitDepth()

void createBitmapContext16BitDepth ( CGImageRef cgImg)

Creates a bitmap graphics context for 16-bit depth per channel processing.

This function is tailored for scenarios requiring high color fidelity, utilizing 16-bit depth per channel to enhance color range and reduce artifacts. It's ideal for high-quality image processing and editing, ensuring the highest fidelity in color information. The process involves validating the source image, allocating a memory buffer with adequate depth, setting up a suitable color space, configuring and rendering into the bitmap context, applying custom image processing, and managing resources efficiently.

Parameters
cgImgThe CGImageRef representing the source image for processing in the 16-bit depth bitmap context.
Note
  • Prioritizes detailed logging for debugging and error tracking, particularly useful given the function's complexity and higher memory demands.
  • Includes commented-out sections for memory diagnostics, indicating a considered approach to monitoring and managing memory usage in high-depth processing scenarios.

Process:

  1. Input Validation: Checks the CGImageRef for nullity, logging any errors encountered.
  2. Dimension Calculation: Determines the necessary dimensions for the bitmap context and pixel data buffer based on the source image's size.
  3. Memory Allocation: Allocates memory for the raw pixel data, factoring in the increased requirements for 16-bit depth per channel.
  4. Color Space Creation: Establishes a Device RGB color space to ensure accurate color reproduction within the context.
  5. Bitmap Context Configuration: Sets up the bitmap context to support 16-bit depth per color channel, including considerations for premultiplied alpha.
  6. Image Rendering: Captures the source CGImage within the bitmap context, maintaining high color depth.
  7. Custom Processing: Applies an "enhanced fuzzing" algorithm to the high-depth pixel data, with an emphasis on thorough diagnostic logging.
  8. Image Generation and Saving: Creates a new CGImage from the context, encapsulates it in a UIImage, and saves the result, denoting its 16-bit depth processing.
  9. Resource Cleanup: Ensures the release of all allocated resources, including the bitmap context and pixel data buffer, to maintain operational cleanliness.

Usage Example:

// Assuming cgImg is a valid CGImageRef
void createBitmapContext16BitDepth(CGImageRef cgImg)
Creates a bitmap graphics context for 16-bit depth per channel processing.

Definition at line 2152 of file xnuimagefuzzer.m.

2152 {
2153 NSLog(@"Creating bitmap context with 16-bit depth per channel");
2154
2155 // Pre-operation memory diagnostic
2156// debugMemoryHandling();
2157
2158 if (!cgImg) {
2159 NSLog(@"Invalid CGImageRef provided.");
2160 return;
2161 }
2162
2163 size_t width = CGImageGetWidth(cgImg);
2164 size_t height = CGImageGetHeight(cgImg);
2165 // Considering 8 bytes per pixel (2 bytes per component * 4 components: RGBA)
2166 size_t bytesPerRow = width * 8;
2167
2168 // Allocate memory for raw image data
2169 unsigned char *rawData = (unsigned char *)calloc(height * bytesPerRow, sizeof(unsigned char));
2170 if (!rawData) {
2171 NSLog(@"Failed to allocate memory for image processing");
2172// debugMemoryHandling(); // Post-failure diagnostic
2173 return;
2174 }
2175
2176 // Create a color space for the bitmap context
2177 CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
2178 if (!colorSpace) {
2179 NSLog(@"Failed to create color space");
2180 free(rawData);
2181// debugMemoryHandling(); // Diagnostic before early exit
2182 return;
2183 }
2184
2185 // Define bitmap info for 16-bit depth per channel
2186 CGBitmapInfo bitmapInfo = kCGImageAlphaPremultipliedLast | kCGBitmapByteOrderDefault;
2187 CGContextRef ctx = CGBitmapContextCreate(rawData, width, height, 16, bytesPerRow, colorSpace, bitmapInfo);
2188 CGColorSpaceRelease(colorSpace);
2189
2190 if (!ctx) {
2191 NSLog(@"Failed to create bitmap context");
2192 free(rawData);
2193// debugMemoryHandling(); // Diagnostic if context creation fails
2194 return;
2195 }
2196
2197 // Draw the CGImage into the bitmap context
2198 CGContextDrawImage(ctx, CGRectMake(0, 0, width, height), cgImg);
2199
2200 // Apply fuzzing logic directly to the bitmap's raw data
2201 NSLog(@"Applying enhanced fuzzing logic to the bitmap context with 16-bit depth");
2202 applyEnhancedFuzzingToBitmapContext(rawData, width, height, YES); // Assuming verbose logging is desired
2203 // Initialize a variable to keep track of unchanged and changed bytes
2204 size_t unchangedCount = 0;
2205 size_t changedCount = 0;
2206
2207
2208 // Check for 0x41 pattern after operations and detect changes
2209 for (size_t i = 0; i < height * bytesPerRow; i++) {
2210 if (rawData[i] == 0x41) {
2211 unchangedCount++;
2212 } else {
2213 // Log the first few changes to avoid flooding the log
2214 if (changedCount < 10) { // Limiting to the first 10 changes for brevity
2215 NSLog(@"Detected change from 0x41 at byte offset %zu, new value: 0x%X", i, rawData[i]);
2216 }
2217 changedCount++;
2218 }
2219 }
2220
2221 // Summarize findings
2222 if (unchangedCount > 0) {
2223 NSLog(@"Detected unchanged 0x41 pattern in %zu places.", unchangedCount);
2224 }
2225 NSLog(@"Detected changes in %zu places.", changedCount);
2226
2227 // Create a new image from the modified context
2228 CGImageRef newCgImg = CGBitmapContextCreateImage(ctx);
2229 if (!newCgImg) {
2230 NSLog(@"Failed to create CGImage from context");
2231 } else {
2232 UIImage *newImage = [UIImage imageWithCGImage:newCgImg];
2233 CGImageRelease(newCgImg);
2234
2235 // Save the fuzzed image with a context-specific identifier
2236 saveFuzzedImage(newImage, @"16bit_depth_png");
2237 saveFuzzedImage(newImage, @"16bit_depth_jpeg");
2238 saveFuzzedImage(newImage, @"16bit_depth_gif");
2239
2240 NSLog(@"Modified UIImage created and saved successfully in both PNG and JPEG formats.");
2241 }
2242
2243 // Cleanup
2244 CGContextRelease(ctx);
2245 free(rawData);
2246// debugMemoryHandling(); // Post-operation diagnostic
2247}
void applyEnhancedFuzzingToBitmapContext(unsigned char *rawData, size_t width, size_t height, BOOL verbose)
Applies enhanced fuzzing techniques to bitmap data.
void saveFuzzedImage(UIImage *image, NSString *contextDescription)
Saves a modified (fuzzed) UIImage to the documents directory.

References applyEnhancedFuzzingToBitmapContext(), and saveFuzzedImage().

Referenced by processImage().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ createBitmapContext1BitMonochrome()

void createBitmapContext1BitMonochrome ( CGImageRef cgImg)

Creates a bitmap context for 1-bit monochrome image processing.

This function is crafted for applications that convert color or grayscale images to monochrome using a 1-bit per pixel format. It's particularly suited for environments where reducing data size is crucial, such as in low-bandwidth or memory-constrained situations, or to achieve a certain aesthetic. The function covers the process from validating the input image, through creating a monochrome bitmap context, to finalizing and releasing resources.

Parameters
cgImgThe CGImageRef representing the source image to be converted to 1-bit monochrome.
Note
The conversion might incorporate techniques like dithering, contrast adjustments, or edge enhancement to optimize the monochrome output. This description assumes a basic approach but acknowledges the potential for more complex processing strategies tailored to specific requirements.

Process:

  1. Input Validation: Confirms the CGImageRef is valid and non-null.
  2. Dimension and Byte Calculation: Sets up the bitmap context based on the source image's dimensions and calculates the minimum bytes per row for 1-bit data.
  3. Bitmap Context Creation: Establishes a monochrome bitmap context without a color space or alpha channel.
  4. Background Initialization: Prepares the bitmap with a white background for consistent monochrome conversion.
  5. Image Drawing: Renders the input image into the context, initiating the conversion to 1-bit color depth.
  6. Bitmap Manipulation: Directly adjusts the bitmap data to refine the monochrome output as needed.
  7. CGImage Generation: Produces a new CGImage reflecting the monochrome conversion.
  8. UIImage Creation: Converts the new CGImage into a UIImage for UIKit compatibility or additional processing.
  9. Optional Saving: Tags and saves the monochrome image for easy storage or retrieval.
  10. Resource Cleanup: Ensures the release of the bitmap context and any other allocated resources.

Usage Example:

// Assuming cgImg is a valid CGImageRef
void createBitmapContext1BitMonochrome(CGImageRef cgImg)
Creates a bitmap context for 1-bit monochrome image processing.

Definition at line 2503 of file xnuimagefuzzer.m.

2503 {
2504 if (!cgImg) {
2505 NSLog(@"Invalid CGImageRef provided.");
2506 return;
2507 }
2508
2509 NSLog(@"Creating bitmap context with 1-bit Monochrome settings");
2510
2511 size_t width = CGImageGetWidth(cgImg);
2512 size_t height = CGImageGetHeight(cgImg);
2513 // Calculate bytes per row for 1 bit per pixel, rounded up to the nearest byte
2514 size_t bytesPerRow = (width + 7) / 8; // Round up to account for partial bytes
2515 CGContextRef ctx = CGBitmapContextCreate(NULL, width, height, 1, bytesPerRow, NULL, kCGImageAlphaNone);
2516 if (!ctx) {
2517 NSLog(@"Failed to create bitmap context with 1-bit Monochrome settings");
2518 return;
2519 }
2520
2521 // Set the fill color to white and fill the context to start with a blank slate
2522 CGContextSetFillColorWithColor(ctx, [UIColor whiteColor].CGColor);
2523 CGContextFillRect(ctx, CGRectMake(0, 0, width, height));
2524
2525 // Draw the CGImage into the bitmap context, adjusting it to fit the 1-bit color depth
2526 CGContextDrawImage(ctx, CGRectMake(0, 0, width, height), cgImg);
2527
2528 // Access the raw pixel data
2529 unsigned char *rawData = CGBitmapContextGetData(ctx);
2530 if (rawData) {
2531 NSLog(@"Converting bitmap data to 1-bit Monochrome");
2532 convertTo1BitMonochrome(rawData, width, height);
2533 }
2534
2535 // Create a new image from the modified context
2536 CGImageRef newCgImg = CGBitmapContextCreateImage(ctx);
2537 if (!newCgImg) {
2538 NSLog(@"Failed to create CGImage from 1-bit Monochrome context");
2539 } else {
2540 UIImage *newImage = [UIImage imageWithCGImage:newCgImg];
2541 CGImageRelease(newCgImg); // Release the created CGImage
2542
2543 // Save the monochrome image with a context-specific identifier
2544 saveMonochromeImage(newImage, @"1Bit_Monochrome");
2545 NSLog(@"Modified UIImage with 1-bit Monochrome settings created and saved successfully.");
2546 }
2547
2548 NSLog(@"Bitmap context with 1-bit Monochrome settings created and handled successfully");
2549 CGContextRelease(ctx);
2550}
void saveMonochromeImage(UIImage *image, NSString *identifier)
Saves a monochrome UIImage with a specified identifier to the documents directory.

References convertTo1BitMonochrome(), and saveMonochromeImage().

Referenced by processImage().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ createBitmapContext32BitFloat4Component()

void createBitmapContext32BitFloat4Component ( CGImageRef cgImg)

Creates a bitmap context with standard RGB settings, applies a fuzzing process to alter the image, and saves the fuzzed image. Useful for testing image processing functionalities or creating varied visual effects.

This function demonstrates how to create a bitmap context, manipulate image pixel data through a fuzzing process, and save the modified image. It covers validating input images, creating bitmap contexts with specific configurations, and applying image processing algorithms to explore and enhance image processing techniques.

Parameters
cgImgThe source image from which to create the bitmap context, represented as a CGImageRef.
Note
  • Memory Management: Demonstrates careful release of resources, including color space and bitmap context, and freeing of dynamically allocated memory.
  • Debugging: Includes commented-out calls to debugMemoryHandling to illustrate potential insertion points for memory diagnostics.
  • Extensibility: The permutation parameter demonstrates the function's potential to apply various fuzzing types based on input parameters, enhancing modularity and maintainability.
  • Logging: Utilizes NSLog for debugging purposes. A more sophisticated logging framework is recommended for production code.
  • Separation of Concerns: Abstracts the actual fuzzing logic into the applyEnhancedFuzzingToBitmapContext function, promoting code modularity and maintainability.

Process Overview:

  1. Validates the CGImageRef input to ensure a source image is provided.
  2. Retrieves source image dimensions and calculates bytes per row for an RGBA pixel format.
  3. Allocates memory for raw pixel data.
  4. Creates a CGColorSpaceRef in the device RGB color space.
  5. Specifies bitmap information for alpha channel handling and byte order.
  6. Creates the bitmap context with allocated memory, color space, and specified bitmap info.
  7. Draws the source image into the bitmap context.
  8. Applies a fuzzing algorithm to manipulate the pixel data directly.
  9. Generates a new CGImageRef from the bitmap context, converts it to UIImage, and saves the result.
  10. Releases allocated resources, including the bitmap context and pixel data memory.

Usage Example:

// Process with all configurations
processImage(myImage, -1);
// Process with a specific configuration
processImage(myImage, 3); // Example: Applies Non-Premultiplied Alpha settings
void processImage(UIImage *image, int permutation)
Processes an image using various bitmap context configurations.

Definition at line 2833 of file xnuimagefuzzer.m.

2833 {
2834 static dispatch_once_t onceToken;
2835 static os_log_t createBitmapContextLog;
2836 dispatch_once(&onceToken, ^{
2837 createBitmapContextLog = os_log_create("cx.srd.xnuimagefuzzer", "CreateBitmapContext");
2838 });
2839
2840 os_signpost_id_t spid = os_signpost_id_generate(createBitmapContextLog);
2841 os_signpost_event_emit(createBitmapContextLog, spid, "Start creating createBitmapContext32BitFloat4Component context");
2842
2843 if (!cgImg) {
2844 NSLog(@"Invalid CGImageRef provided.");
2845 return;
2846 }
2847
2848 NSLog(@"Creating bitmap context with 32-bit float, 4-component settings");
2849
2850 size_t width = CGImageGetWidth(cgImg);
2851 size_t height = CGImageGetHeight(cgImg);
2852 size_t bytesPerRow = width * 4 * sizeof(float);
2853
2854 CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
2855 if (!colorSpace) {
2856 NSLog(@"Failed to create color space");
2857 return;
2858 }
2859
2860 CGBitmapInfo bitmapInfo = kCGImageAlphaPremultipliedLast | kCGBitmapFloatComponents;
2861 CGContextRef ctx = CGBitmapContextCreate(NULL, width, height, 32, bytesPerRow, colorSpace, bitmapInfo);
2862 CGColorSpaceRelease(colorSpace);
2863
2864 if (!ctx) {
2865 NSLog(@"Failed to create bitmap context with 32-bit float, 4-component settings");
2866 return;
2867 }
2868
2869 CGContextDrawImage(ctx, CGRectMake(0, 0, width, height), cgImg);
2870
2871 NSLog(@"Applying enhanced fuzzing logic to the bitmap context");
2872 // Placeholder for enhanced fuzzing logic application. Implement this function based on your fuzzing requirements.
2873 applyEnhancedFuzzingToBitmapContextWithFloats((float*)CGBitmapContextGetData(ctx), width, height, YES);
2874
2875 CGImageRef newCgImg = CGBitmapContextCreateImage(ctx);
2876 if (!newCgImg) {
2877 NSLog(@"Failed to create CGImage from context");
2878 } else {
2879 UIImage *newImage = [UIImage imageWithCGImage:newCgImg];
2880 CGImageRelease(newCgImg);
2881 // Placeholder for saving the fuzzed image. Implement this function to save your image as needed.
2882 saveFuzzedImage(newImage, @"32bit_float4_png");
2883 saveFuzzedImage(newImage, @"32bit_float4_jpeg");
2884 saveFuzzedImage(newImage, @"32bit_float4_gif");
2885 NSLog(@"Modified UIImage with 32-bit float, 4-component settings created and saved successfully for PNG, JPG and GIF.");
2886 }
2887
2888 CGContextRelease(ctx);
2889
2890 os_signpost_event_emit(createBitmapContextLog, spid, "Finished creating bitmap context for 32bit_float4");
2891}

References applyEnhancedFuzzingToBitmapContextWithFloats(), and saveFuzzedImage().

Referenced by processImage().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ createBitmapContext8BitInvertedColors()

void createBitmapContext8BitInvertedColors ( CGImageRef cgImg)

Transforms the color representation of an image by inverting its colors and applying an 8-bit color depth.

This function is designed for manipulating a bitmap graphics context to invert the RGB values of each pixel in a given CGImageRef, while keeping the alpha channel unchanged. It applies an "enhanced fuzzing logic" to the modified pixel data, making it suitable for creating visual negatives, enhancing image contrast, or evaluating the robustness of image processing algorithms. The color inversion process creates complementary colors for each pixel, offering a straightforward method for achieving visual effects or testing.

The setup includes configuring a bitmap context optimized for color inversion and specifying byte order and alpha channel handling. It involves iterating over raw pixel data for manual color inversion and integrating enhanced fuzzing routines for further pixel manipulation. The function concludes by generating a new CGImage that encapsulates all modifications, which is then saved with a unique identifier.

Resource management is a key aspect, ensuring efficient memory use and necessitating the implementation of fuzzing and saving routines elsewhere within the application's codebase.

Parameters
cgImgThe CGImageRef representing the source image to be transformed. This parameter must not be NULL to ensure proper function execution.
Note
Utilizing this function requires careful consideration of the source image's format and the intended outcome, particularly in terms of color depth and the specific effects of the enhanced fuzzing logic. The reliance on external methods for the fuzzing process and saving the modified image highlights the need for a comprehensive approach to image processing within the application.

Example Usage:

CGImageRef sourceImage = ...; // Assume this is a valid CGImageRef
createBitmapContextForColorInversionAndFuzzing(sourceImage);

Definition at line 2735 of file xnuimagefuzzer.m.

2735 {
2736 if (!cgImg) {
2737 NSLog(@"Invalid CGImageRef provided.");
2738 return;
2739 }
2740
2741 NSLog(@"Creating bitmap context with 8-bit depth, inverted colors");
2742
2743 size_t width = CGImageGetWidth(cgImg);
2744 size_t height = CGImageGetHeight(cgImg);
2745 CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); // Create color space
2746 if (!colorSpace) {
2747 NSLog(@"Failed to create color space for 8-bit depth, inverted colors");
2748 return;
2749 }
2750
2751 CGContextRef ctx = CGBitmapContextCreate(NULL, width, height, 8, width * 4, colorSpace, kCGImageAlphaNoneSkipLast | kCGBitmapByteOrder32Little);
2752 CGColorSpaceRelease(colorSpace); // Release the color space object
2753
2754 if (!ctx) {
2755 NSLog(@"Failed to create bitmap context with 8-bit depth, inverted colors");
2756 return;
2757 }
2758
2759 // Draw the CGImage into the bitmap context
2760 CGContextDrawImage(ctx, CGRectMake(0, 0, width, height), cgImg);
2761
2762 // Access the raw pixel data
2763 unsigned char *rawData = CGBitmapContextGetData(ctx);
2764 if (rawData) {
2765 // Invert colors for each pixel
2766 for (size_t i = 0; i < width * height * 4; i += 4) {
2767 rawData[i] = 255 - rawData[i]; // Invert Red
2768 rawData[i + 1] = 255 - rawData[i + 1]; // Invert Green
2769 rawData[i + 2] = 255 - rawData[i + 2]; // Invert Blue
2770 // Alpha is skipped
2771 }
2772
2773 // Apply enhanced fuzzing with string injection logic
2774 applyEnhancedFuzzingToBitmapContext(rawData, width, height, YES);
2775 }
2776
2777 // Create a new image from the modified context
2778 CGImageRef newCgImg = CGBitmapContextCreateImage(ctx);
2779 if (!newCgImg) {
2780 NSLog(@"Failed to create CGImage from 8-bit depth, inverted colors");
2781 } else {
2782 UIImage *newImage = [UIImage imageWithCGImage:newCgImg];
2783 CGImageRelease(newCgImg); // Release the created CGImage
2784
2785 // Save the fuzzed image with a specific identifier
2786 saveFuzzedImage(newImage, @"8Bit_InvertedColors_png");
2787 saveFuzzedImage(newImage, @"8Bit_InvertedColors_jpeg");
2788 saveFuzzedImage(newImage, @"8Bit_InvertedColors_gif");
2789 NSLog(@"Modified UIImage with createBitmapContext8BitInvertedColors settings created and saved successfully for PNG, JPG and GIF.");
2790 }
2791
2792 CGContextRelease(ctx); // Release the bitmap context
2793}

References applyEnhancedFuzzingToBitmapContext(), and saveFuzzedImage().

Referenced by processImage().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ createBitmapContextAlphaOnly()

void createBitmapContextAlphaOnly ( CGImageRef cgImg)

Creates a bitmap context for alpha channel manipulation of a CGImageRef.

This function is specifically designed for scenarios requiring isolated handling of image transparency, excluding color data. It supports applications in graphics editing, custom rendering, and transparency management by focusing exclusively on the alpha channel. The function validates the source image, configures a dedicated bitmap context for alpha data, applies custom modifications to transparency levels, and manages resource cleanup effectively.

Parameters
cgImgThe CGImageRef representing the source image from which the alpha channel will be extracted and processed.

Implementation Notes:

  • Assumes the presence of an alpha channel in the input image. In the absence of transparency in the source image, extracted alpha data may lack significance.
  • References the applyEnhancedFuzzingToBitmapContextAlphaOnly function for specific alpha data manipulation, aimed at testing or enhancing transparency effects.
  • Highlighting the challenge of utilizing processed alpha data for image reconstruction, as this operation concentrates on transparency without color components.
  • Includes indications for debugMemoryHandling to facilitate memory management diagnostics, crucial for optimizing resource use in constrained environments.

Process:

  1. Input Validation: Ensures the CGImageRef is suitable for transparency extraction and processing.
  2. Dimension Retrieval: Accurately configures the bitmap context based on the source image's dimensions.
  3. Memory Allocation: Dedicates a memory buffer for storing alpha data, reflecting opacity with one byte per pixel.
  4. Bitmap Context Creation: Establishes a context focused on alpha channel information, omitting color space configuration.
  5. Alpha Extraction: Draws the source image into the context, isolating the alpha channel data.
  6. Transparency Manipulation: Applies custom fuzzing to the alpha data, adjusting transparency for specific effects or testing.
  7. Resource Cleanup: Releases the bitmap context and alpha data array, ensuring no memory leaks.

Usage Example:

// Assuming cgImg is a valid CGImageRef with an alpha channel
void createBitmapContextAlphaOnly(CGImageRef cgImg)
Creates a bitmap context for alpha channel manipulation of a CGImageRef.

Definition at line 2406 of file xnuimagefuzzer.m.

2406 {
2407 NSLog(@"Creating bitmap context for Alpha channel only");
2408
2409 // Pre-operation memory diagnostic
2410// debugMemoryHandling();
2411
2412 if (!cgImg) {
2413 NSLog(@"Invalid CGImageRef provided.");
2414 return;
2415 }
2416
2417 size_t width = CGImageGetWidth(cgImg);
2418 size_t height = CGImageGetHeight(cgImg);
2419 size_t bytesPerRow = width; // 1 byte per pixel for Alpha only
2420
2421 // Allocate memory for raw alpha data
2422 unsigned char *alphaData = (unsigned char *)calloc(height * bytesPerRow, sizeof(unsigned char));
2423 if (!alphaData) {
2424 NSLog(@"Failed to allocate memory for alpha channel processing");
2425// debugMemoryHandling(); // Post-failure diagnostic
2426 return;
2427 }
2428
2429 // Since we're dealing with alpha only, no color space is required
2430 // Adjusting bitmap info to accommodate alpha data correctly
2431 CGBitmapInfo bitmapInfo = kCGImageAlphaOnly | kCGBitmapByteOrderDefault;
2432
2433 CGContextRef ctx = CGBitmapContextCreate(alphaData, width, height, 8, bytesPerRow, NULL, bitmapInfo);
2434
2435 if (!ctx) {
2436 NSLog(@"Failed to create bitmap context for Alpha channel");
2437 free(alphaData);
2438// debugMemoryHandling(); // Diagnostic if context creation fails
2439 return;
2440 }
2441
2442 // Drawing the alpha channel into the context
2443 // Assuming the cgImg already contains the alpha channel we want to process
2444 CGContextDrawImage(ctx, CGRectMake(0, 0, width, height), cgImg);
2445
2446 // Apply fuzzing logic directly to the alpha data
2447 NSLog(@"Applying enhanced fuzzing logic to the Alpha-only bitmap context");
2448 // Note: The applyEnhancedFuzzingToBitmapContext function needs to be adjusted to work with alphaData
2449 applyEnhancedFuzzingToBitmapContextAlphaOnly(alphaData, width, height, YES); // Assuming verbose logging is desired
2450
2451 // Creating a new image from the modified context might not be directly applicable
2452 // as we're dealing with alpha channel only. Further processing might be required
2453 // to utilize this alpha data with another image or for masking.
2454 CGImageRef newCgImg = CGBitmapContextCreateImage(ctx);
2455 if (!newCgImg) {
2456 NSLog(@"Failed to create CGImage from context");
2457 } else {
2458 UIImage *newImage = [UIImage imageWithCGImage:newCgImg];
2459 CGImageRelease(newCgImg);
2460
2461 saveFuzzedImage(newImage, @"alpha_channel_png");
2462 saveFuzzedImage(newImage, @"alpha_channel_jpeg");
2463 saveFuzzedImage(newImage, @"alpha_channel_gif");
2464
2465 NSLog(@"Modified UIImage created and saved successfully.");
2466 }
2467 // Cleanup and resource management
2468 CGContextRelease(ctx);
2469 free(alphaData);
2470// debugMemoryHandling(); // Post-operation diagnostic
2471
2472 NSLog(@"Alpha-only bitmap context processing completed.");
2473}
void applyEnhancedFuzzingToBitmapContextAlphaOnly(unsigned char *alphaData, size_t width, size_t height, BOOL verboseLogging)
Applies enhanced fuzzing techniques to the alpha channel of bitmap pixel data.

References applyEnhancedFuzzingToBitmapContextAlphaOnly(), and saveFuzzedImage().

Referenced by processImage().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ createBitmapContextBigEndian()

void createBitmapContextBigEndian ( CGImageRef cgImg)

Creates a bitmap context with Big Endian byte ordering for image data processing.

This function is designed for scenarios where Big Endian representation is crucial for the consistency of pixel color data in memory, particularly in systems or applications expecting this byte order. It validates the input image, establishes an appropriate RGB color space, configures a bitmap context for Big Endian processing, applies an "enhanced fuzzing logic" to the pixel data for testing or artistic purposes, and finalizes the process by releasing resources and saving the modified image.

Parameters
cgImgThe CGImageRef representing the original image for processing. It is essential that this image is not null to proceed with the transformation.

Process:

  1. Input Validation: Ensures the CGImageRef provided is valid and not null.
  2. Color Space Creation: Sets up a color space suitable for RGB data manipulation.
  3. Bitmap Context Configuration: Initiates a bitmap context with Big Endian byte ordering to prioritize the most significant byte in pixel color data.
  4. Image Rendering: Draws the original image into the configured bitmap context, preparing for data manipulation.
  5. Pixel Data Fuzzing: Applies an "enhanced fuzzing logic" directly to the raw pixel data, aiming to test algorithm resilience, simulate effects, or introduce noise.
  6. CGImage Generation: Creates a new CGImage from the context to encapsulate the modifications.
  7. Resource Cleanup: Releases the color space, bitmap context, and any other allocated resources to ensure efficient memory management.
  8. Image Saving: Marks the transformation's completion by saving the modified image with a unique identifier.

Example Usage:

// Assuming cgImg is a valid CGImageRef
void createBitmapContextBigEndian(CGImageRef cgImg)
Creates a bitmap context with Big Endian byte ordering for image data processing.

Definition at line 2578 of file xnuimagefuzzer.m.

2578 {
2579 if (!cgImg) {
2580 NSLog(@"Invalid CGImageRef provided.");
2581 return;
2582 }
2583
2584 NSLog(@"Creating bitmap context with Big Endian settings");
2585
2586 size_t width = CGImageGetWidth(cgImg);
2587 size_t height = CGImageGetHeight(cgImg);
2588 CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); // Create color space
2589 if (!colorSpace) {
2590 NSLog(@"Failed to create color space for Big Endian settings");
2591 return;
2592 }
2593
2594 CGContextRef ctx = CGBitmapContextCreate(NULL, width, height, 8, width * 4, colorSpace, kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
2595 CGColorSpaceRelease(colorSpace); // Release the color space object
2596
2597 if (!ctx) {
2598 NSLog(@"Failed to create bitmap context with Big Endian settings");
2599 return;
2600 }
2601
2602 // Draw the CGImage into the bitmap context
2603 CGContextDrawImage(ctx, CGRectMake(0, 0, width, height), cgImg);
2604
2605 // Access the raw pixel data
2606 unsigned char *rawData = CGBitmapContextGetData(ctx);
2607 if (rawData) {
2608 NSLog(@"Applying enhanced fuzzing logic to the Big Endian bitmap context");
2609 applyEnhancedFuzzingToBitmapContext(rawData, width, height, YES);
2610 }
2611
2612 // Create a new image from the modified context
2613 CGImageRef newCgImg = CGBitmapContextCreateImage(ctx);
2614 if (!newCgImg) {
2615 NSLog(@"Failed to create CGImage from Big Endian context");
2616 } else {
2617 UIImage *newImage = [UIImage imageWithCGImage:newCgImg];
2618 CGImageRelease(newCgImg); // Release the created CGImage
2619
2620 // Save the fuzzed image with a context-specific identifier
2621 saveFuzzedImage(newImage, @"Big_Endian_png");
2622 saveFuzzedImage(newImage, @"Big_Endian_jpeg");
2623 saveFuzzedImage(newImage, @"Big_Endian_gif");
2624 NSLog(@"Modified UIImage with Big Endian settings created and saved successfully in PNG, JPEG and GIF.");
2625 }
2626
2627 NSLog(@"Bitmap context with Big Endian settings created and handled successfully for PNG, JPG and GIF");
2628 CGContextRelease(ctx); // Release the bitmap context
2629}

References applyEnhancedFuzzingToBitmapContext(), and saveFuzzedImage().

Referenced by processImage().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ createBitmapContextGrayscale()

void createBitmapContextGrayscale ( CGImageRef cgImg)

Definition at line 2251 of file xnuimagefuzzer.m.

2251 {
2252 NSLog(@"Grayscale image processing is not yet implemented.");
2253 // No further processing or memory allocations
2254}

◆ createBitmapContextHDRFloatComponents()

void createBitmapContextHDRFloatComponents ( CGImageRef cgImg)

Initializes a bitmap context for HDR content with floating-point components.

This function is pivotal for handling High Dynamic Range (HDR) images, enabling the precise manipulation of extended color and brightness ranges. By employing floating-point components and an HDR-compatible color space, it facilitates the processing of images with significantly broader luminance and color gamut than traditional 8-bit or 16-bit formats allow. The function outlines steps for validating the source image, allocating memory for HDR data, setting up an HDR-compatible color space and bitmap context, and applying custom image processing.

Parameters
cgImgThe CGImageRef representing the source image for processing in the HDR bitmap context.
Note
  • The function's design caters to advanced image processing experiments, including dynamic manipulation and fuzzing based on varying data inputs.
  • Assumes the use of a mechanism to cycle through predefined strings for the fuzzing process, illustrating the method's adaptability to different parameters or data influences.

Process:

  1. Input Validation: Confirms the CGImageRef is valid and not null.
  2. Memory Allocation: Allocates a buffer for floating-point raw data, accounting for HDR's extensive data size requirements.
  3. Color Space Creation: Initiates an HDR-compatible color space (kCGColorSpaceExtendedLinearSRGB) to accurately handle HDR images' expanded gamut and luminance.
  4. Bitmap Context Setup: Configures the bitmap context with 32 bits per component in floating-point format, suitable for HDR content's nuanced representation.
  5. Image Rendering: Draws the source CGImage into the context, ensuring it captures the high precision of HDR.
  6. Custom Processing: Applies a custom fuzzing process to the bitmap data, using predefined strings to demonstrate or test specific effects.
  7. Image Generation and Saving: Creates a new CGImage from the modified context, then a UIImage, facilitating its use within UIKit applications. Saves the processed image with a relevant identifier.
  8. Resource Cleanup: Releases all allocated resources, including the color space, bitmap context, and memory buffer, to prevent memory leaks.

Usage Example:

// Assuming cgImg is a valid CGImageRef
void createBitmapContextHDRFloatComponents(CGImageRef cgImg)
Initializes a bitmap context for HDR content with floating-point components.

Definition at line 2284 of file xnuimagefuzzer.m.

2284 {
2285 NSLog(@"Creating bitmap context with HDR and floating-point components");
2286
2287 if (!cgImg) {
2288 NSLog(@"Invalid CGImageRef provided.");
2289 return;
2290 }
2291
2292 size_t width = CGImageGetWidth(cgImg);
2293 size_t height = CGImageGetHeight(cgImg);
2294 size_t bytesPerRow = width * 16; // Considering 16 bytes per pixel for HDR
2295
2296 // Allocate memory for raw image data
2297 float *rawData = (float *)calloc(height * bytesPerRow, sizeof(float));
2298 if (!rawData) {
2299 NSLog(@"Failed to allocate memory for image processing");
2300 return;
2301 }
2302
2303 CGColorSpaceRef colorSpace = CGColorSpaceCreateWithName(kCGColorSpaceExtendedLinearSRGB);
2304 if (!colorSpace) {
2305 NSLog(@"Failed to create HDR color space");
2306 free(rawData);
2307 return;
2308 }
2309
2310 CGBitmapInfo bitmapInfo = kCGImageAlphaPremultipliedLast | kCGBitmapFloatComponents | kCGBitmapByteOrder32Little;
2311 CGContextRef ctx = CGBitmapContextCreate(rawData, width, height, 32, bytesPerRow, colorSpace, bitmapInfo);
2312 CGColorSpaceRelease(colorSpace);
2313
2314 if (!ctx) {
2315 NSLog(@"Failed to create bitmap context for HDR");
2316 free(rawData);
2317 return;
2318 }
2319
2320 CGContextDrawImage(ctx, CGRectMake(0, 0, width, height), cgImg);
2321
2322 NSLog(@"Applying enhanced fuzzing logic to the HDR bitmap context");
2323
2324 // Cycle through injection strings or select based on specific criteria
2325 static int currentStringIndex = 0; // Example: simple cycling mechanism
2326 applyEnhancedFuzzingToBitmapContextWithFloats(rawData, width, height, YES);
2327 currentStringIndex = (currentStringIndex + 1) % NUMBER_OF_STRINGS; // Move to the next string for the next call
2328
2329 // Initialize a variable to keep track of unchanged and changed bytes
2330 size_t unchangedCount = 0;
2331 size_t changedCount = 0;
2332
2333 // Check for 0x41 pattern after operations and detect changes
2334 for (size_t i = 0; i < height * bytesPerRow; i++) {
2335 if (rawData[i] == 0x41) {
2336 unchangedCount++;
2337 } else {
2338 // Log the first few changes to avoid flooding the log
2339 if (changedCount < 10) { // Limiting to the first 10 changes for brevity
2340 // Using a union to reinterpret the float's bits as an unsigned int for logging
2341 union {
2342 float f;
2343 unsigned int u;
2344 } floatToHex;
2345
2346 floatToHex.f = rawData[i]; // Assign the float value to the union
2347
2348 NSLog(@"Detected change from 0x41 at byte offset %zu, new value: 0x%X", i, floatToHex.u);
2349 }
2350 changedCount++;
2351 }
2352 }
2353
2354 // Summarize findings
2355 if (unchangedCount > 0) {
2356 NSLog(@"Detected unchanged 0x41 pattern in %zu places.", unchangedCount);
2357 }
2358 NSLog(@"Detected changes in %zu places.", changedCount);
2359
2360 CGImageRef newCgImg = CGBitmapContextCreateImage(ctx);
2361 if (!newCgImg) {
2362 NSLog(@"Failed to create CGImage from HDR context");
2363 } else {
2364 UIImage *newImage = [UIImage imageWithCGImage:newCgImg];
2365 CGImageRelease(newCgImg);
2366
2367 saveFuzzedImage(newImage, @"hdr_float_png");
2368 saveFuzzedImage(newImage, @"hdr_float_jpeg");
2369 saveFuzzedImage(newImage, @"hdr_float_gif");
2370 NSLog(@"Modified UIImage with HDR and floating-point components created and saved successfully in both PNG, JPEG and GIF formats.");
2371 }
2372
2373 CGContextRelease(ctx);
2374 free(rawData);
2375}

References applyEnhancedFuzzingToBitmapContextWithFloats(), NUMBER_OF_STRINGS, and saveFuzzedImage().

Referenced by processImage().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ createBitmapContextLittleEndian()

void createBitmapContextLittleEndian ( CGImageRef cgImg)

Initializes a bitmap context with Little Endian settings for image data processing.

This function focuses on preparing and manipulating a bitmap graphics context optimized for Little Endian byte ordering, suitable for systems and applications that require the least significant byte to be stored first. It involves creating an RGB color space, setting up the bitmap context for Little Endian processing, applying predefined fuzzing algorithms to pixel data, and finalizing the modified image. The process is aimed at testing image processing capabilities, creating visual effects, or introducing distortions through direct pixel manipulation.

Parameters
cgImgThe CGImageRef representing the image to be processed, which must not be null to ensure successful transformation.

Process:

  1. Input Validation: Confirms that the provided CGImageRef is valid and non-null.
  2. Color Space and Context Setup: Establishes an RGB color space and creates a bitmap context tailored for Little Endian byte ordering.
  3. Image Drawing and Pixel Manipulation: Renders the original image into the context, then employs "enhanced fuzzing logic" for direct pixel data alteration.
  4. CGImage Creation: Generates a new CGImage from the modified bitmap context, capturing the changes.
  5. Resource Management: Releases the color space and bitmap context to manage memory usage effectively.
  6. Image Saving: Completes the modification process by saving the altered image with a specific identifier, integrating external routines for saving and potentially additional processing.

Example Usage:

// Assuming cgImg is a valid CGImageRef
void createBitmapContextLittleEndian(CGImageRef cgImg)
Initializes a bitmap context with Little Endian settings for image data processing.

Definition at line 2655 of file xnuimagefuzzer.m.

2655 {
2656 if (!cgImg) {
2657 NSLog(@"Invalid CGImageRef provided.");
2658 return;
2659 }
2660
2661 NSLog(@"Creating bitmap context with Little Endian settings");
2662
2663 size_t width = CGImageGetWidth(cgImg);
2664 size_t height = CGImageGetHeight(cgImg);
2665 CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); // Create color space
2666 if (!colorSpace) {
2667 NSLog(@"Failed to create color space for Little Endian settings");
2668 return;
2669 }
2670
2671 CGContextRef ctx = CGBitmapContextCreate(NULL, width, height, 8, width * 4, colorSpace, kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Little);
2672 CGColorSpaceRelease(colorSpace); // Release the color space object
2673
2674 if (!ctx) {
2675 NSLog(@"Failed to create bitmap context with Little Endian settings");
2676 return;
2677 }
2678
2679 // Draw the CGImage into the bitmap context
2680 CGContextDrawImage(ctx, CGRectMake(0, 0, width, height), cgImg);
2681
2682 // Access the raw pixel data
2683 unsigned char *rawData = CGBitmapContextGetData(ctx);
2684 if (rawData) {
2685 NSLog(@"Applying enhanced fuzzing logic to the Little Endian bitmap context");
2686 applyEnhancedFuzzingToBitmapContext(rawData, width, height, YES);
2687 }
2688
2689 // Create a new image from the modified context
2690 CGImageRef newCgImg = CGBitmapContextCreateImage(ctx);
2691 if (!newCgImg) {
2692 NSLog(@"Failed to create CGImage from Little Endian context");
2693 } else {
2694 UIImage *newImage = [UIImage imageWithCGImage:newCgImg];
2695 CGImageRelease(newCgImg); // Release the created CGImage
2696
2697 // Save the fuzzed image with a context-specific identifier
2698 saveFuzzedImage(newImage, @"Little_Endian_png");
2699 saveFuzzedImage(newImage, @"Little_Endian_jpeg");
2700 saveFuzzedImage(newImage, @"Little_Endian_gif");
2701 NSLog(@"Modified UIImage with Little Endian settings created and saved successfully for PNG, JPG and GIF.");
2702 }
2703
2704 NSLog(@"Bitmap context with Little Endian settings created successfully");
2705 CGContextRelease(ctx); // Release the bitmap context
2706}

References applyEnhancedFuzzingToBitmapContext(), and saveFuzzedImage().

Referenced by processImage().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ createBitmapContextNonPremultipliedAlpha()

void createBitmapContextNonPremultipliedAlpha ( CGImageRef cgImg)

Creates a bitmap graphics context with Non-Premultiplied Alpha settings for processing a CGImage.

Tailored for scenarios where non-premultiplied alpha handling is crucial, this function facilitates precise control over the alpha channel during image processing. It's particularly useful where premultiplication could obscure details or degrade quality. The function outlines a structured approach to creating a bitmap context that maintains the integrity of the alpha channel, applying modifications through an "enhanced fuzzing" process, and concluding with the saving of the altered image.

The procedure includes validating the CGImageRef, memory allocation for pixel data, setting up a Device RGB color space, configuring bitmap context parameters for non-premultiplied alpha, image rendering, applying custom processing logic, and resource cleanup.

Parameters
cgImgThe CGImageRef representing the image to be processed, used as the source for the bitmap context.
Note
  • Emphasizes meticulous memory management to prevent leaks, including the release of the bitmap context and allocated pixel data.
  • Incorporates diagnostic logging at various stages to support debugging and ensure processing accuracy.

Process:

  1. Validation: Ensures the CGImageRef is non-null and valid for processing.
  2. Memory Allocation: Determines the required dimensions and allocates memory for storing the image's pixel data.
  3. Color Space Setup: Creates a Device RGB color space for the bitmap context, essential for accurate color reproduction.
  4. Bitmap Context Configuration: Establishes a bitmap context tailored for non-premultiplied alpha, specifying relevant bitmap info flags.
  5. Image Rendering: Draws the source CGImage into the bitmap context, preserving raw pixel data integrity.
  6. Custom Processing: Applies an "enhanced fuzzing" algorithm to the pixel data, modifying the image's appearance or characteristics.
  7. Image Generation and Saving: Converts the processed bitmap context into a new CGImage and a UIImage, saving the result with a distinctive identifier.
  8. Resource Cleanup: Carefully releases the bitmap context and frees the memory allocated for pixel data, ensuring no memory leaks occur.

Usage Example:

// Assuming cgImg is a valid CGImageRef
void createBitmapContextNonPremultipliedAlpha(CGImageRef cgImg)
Creates a bitmap graphics context with Non-Premultiplied Alpha settings for processing a CGImage.

Definition at line 2035 of file xnuimagefuzzer.m.

2035 {
2036 NSLog(@"Creating bitmap context with Non-Premultiplied Alpha settings");
2037
2038 if (!cgImg) {
2039 NSLog(@"Invalid CGImageRef provided.");
2040 return;
2041 }
2042
2043 size_t width = CGImageGetWidth(cgImg);
2044 size_t height = CGImageGetHeight(cgImg);
2045 size_t bytesPerRow = width * 4; // RGBA format
2046
2047 // Allocate memory for raw image data
2048 unsigned char *rawData = (unsigned char *)calloc(height * bytesPerRow, sizeof(unsigned char));
2049 if (!rawData) {
2050 NSLog(@"Failed to allocate memory for image processing");
2051 return;
2052 }
2053
2054 // Create a color space for the bitmap context
2055 CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
2056 if (!colorSpace) {
2057 NSLog(@"Failed to create color space");
2058 free(rawData);
2059 return;
2060 }
2061
2062 // Define bitmap info with non-premultiplied alpha
2063 CGBitmapInfo bitmapInfo = kCGImageAlphaNoneSkipLast | kCGBitmapByteOrder32Big;
2064 CGContextRef ctx = CGBitmapContextCreate(rawData, width, height, 8, bytesPerRow, colorSpace, bitmapInfo);
2065 CGColorSpaceRelease(colorSpace);
2066
2067 if (!ctx) {
2068 NSLog(@"Failed to create bitmap context");
2069 free(rawData);
2070 return;
2071 }
2072
2073 // Draw the CGImage into the bitmap context
2074 CGContextDrawImage(ctx, CGRectMake(0, 0, width, height), cgImg);
2075
2076 // Apply fuzzing logic directly to the bitmap's raw data
2077 NSLog(@"Applying enhanced fuzzing logic to the bitmap context with non-premultiplied alpha");
2078 applyEnhancedFuzzingToBitmapContext(rawData, width, height, YES); // Assuming verbose logging is desired
2079 // Initialize a variable to keep track of unchanged and changed bytes
2080 size_t unchangedCount = 0;
2081 size_t changedCount = 0;
2082
2083 // Check for 0x41 pattern after operations and detect changes
2084 for (size_t i = 0; i < height * bytesPerRow; i++) {
2085 if (rawData[i] == 0x41) {
2086 unchangedCount++;
2087 } else {
2088 // Log the first few changes to avoid flooding the log
2089 if (changedCount < 10) { // Limiting to the first 10 changes for brevity
2090 NSLog(@"Detected change from 0x41 at byte offset %zu, new value: 0x%X", i, rawData[i]);
2091 }
2092 changedCount++;
2093 }
2094 }
2095
2096 // Summarize findings
2097 if (unchangedCount > 0) {
2098 NSLog(@"Detected unchanged 0x41 pattern in %zu places.", unchangedCount);
2099 }
2100 NSLog(@"Detected changes in %zu places.", changedCount);
2101
2102 // Create a new image from the modified context
2103 CGImageRef newCgImg = CGBitmapContextCreateImage(ctx);
2104 if (!newCgImg) {
2105 NSLog(@"Failed to create CGImage from context");
2106 } else {
2107 UIImage *newImage = [UIImage imageWithCGImage:newCgImg];
2108 CGImageRelease(newCgImg);
2109
2110 // Save the fuzzed image with a context-specific identifier
2111 saveFuzzedImage(newImage, @"non_premultiplied_alpha_png");
2112 saveFuzzedImage(newImage, @"non_premultiplied_alpha_jpeg");
2113 saveFuzzedImage(newImage, @"non_premultiplied_alpha_gif");
2114
2115 NSLog(@"Modified UIImage created and saved successfully for non-premultiplied alpha in both PNG, JPEG and GIF formats.");
2116 }
2117
2118 // Cleanup
2119 CGContextRelease(ctx);
2120 free(rawData);
2121}

References applyEnhancedFuzzingToBitmapContext(), and saveFuzzedImage().

Referenced by processImage().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ createBitmapContextPremultipliedFirstAlpha()

void createBitmapContextPremultipliedFirstAlpha ( CGImageRef cgImg)

Creates a bitmap context with Premultiplied First Alpha settings and applies image processing.

This function initializes a bitmap context optimized for image processing with premultiplied first alpha settings, drawing a provided CGImage into this context. It fills the allocated memory with a 0x41 pattern to facilitate debugging and security analysis by identifying unused or inefficiently managed memory regions. After processing the image, it checks for any unchanged memory areas and logs their locations, offering insights into memory utilization.

Parameters
cgImgA CGImageRef representing the source image to be transformed. Must not be NULL.

Utilizing a 0x41 pattern fill and subsequent check, this function aids in debugging memory handling and potentially identifying security vulnerabilities related to buffer overflow or improper memory management. It's designed for enhanced debugging and should be used with consideration for its performance impact in production environments.

Example Usage:

CGImageRef sourceImage = CGImageCreate(...); // Create or obtain a CGImageRef
CGImageRelease(sourceImage); // Clean up the source image if it's no longer needed
void createBitmapContextPremultipliedFirstAlpha(CGImageRef cgImg)
Creates a bitmap context with Premultiplied First Alpha settings and applies image processing.
Note
Ensure that the CGImageRef provided to this function is valid. The function logs detailed information about its operation, especially detecting unchanged memory areas after processing, which can be instrumental in identifying inefficiencies or vulnerabilities.

Definition at line 1919 of file xnuimagefuzzer.m.

1919 {
1920 NSLog(@"Creating bitmap context with Premultiplied First Alpha settings");
1921
1922 if (!cgImg) {
1923 NSLog(@"Invalid CGImageRef provided.");
1924 return;
1925 }
1926
1927 size_t width = CGImageGetWidth(cgImg);
1928 size_t height = CGImageGetHeight(cgImg);
1929 size_t bytesPerRow = width * 4;
1930
1931 unsigned char *rawData = (unsigned char *)calloc(height * bytesPerRow, sizeof(unsigned char));
1932 if (!rawData) {
1933 NSLog(@"Failed to allocate memory for image processing");
1934 return;
1935 }
1936
1937 // Initialize memory with 0x41 pattern
1938 memset(rawData, 0x41, height * bytesPerRow);
1939
1940 CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
1941 if (!colorSpace) {
1942 NSLog(@"Failed to create color space");
1943 free(rawData);
1944 return;
1945 }
1946
1947 CGBitmapInfo bitmapInfo = kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Big;
1948 CGContextRef ctx = CGBitmapContextCreate(rawData, width, height, 8, bytesPerRow, colorSpace, bitmapInfo);
1949 CGColorSpaceRelease(colorSpace);
1950
1951 if (!ctx) {
1952 NSLog(@"Failed to create bitmap context");
1953 free(rawData);
1954 return;
1955 }
1956
1957 CGContextDrawImage(ctx, CGRectMake(0, 0, width, height), cgImg);
1958
1959 NSLog(@"Applying enhanced fuzzing logic to the bitmap context");
1960 applyEnhancedFuzzingToBitmapContext(rawData, width, height, YES);
1961
1962 // Initialize a variable to keep track of unchanged and changed bytes
1963 size_t unchangedCount = 0;
1964 size_t changedCount = 0;
1965
1966 // Check for 0x41 pattern after operations and detect changes
1967 for (size_t i = 0; i < height * bytesPerRow; i++) {
1968 if (rawData[i] == 0x41) {
1969 unchangedCount++;
1970 } else {
1971 // Log the first few changes to avoid flooding the log
1972 if (changedCount < 10) { // Limiting to the first 10 changes for brevity
1973 NSLog(@"Detected change from 0x41 at byte offset %zu, new value: 0x%X", i, rawData[i]);
1974 }
1975 changedCount++;
1976 }
1977 }
1978
1979 // Summarize findings
1980 if (unchangedCount > 0) {
1981 NSLog(@"Detected unchanged 0x41 pattern in %zu places.", unchangedCount);
1982 }
1983 NSLog(@"Detected changes in %zu places.", changedCount);
1984
1985 CGImageRef newCgImg = CGBitmapContextCreateImage(ctx);
1986 if (!newCgImg) {
1987 NSLog(@"Failed to create CGImage from context");
1988 } else {
1989 UIImage *newImage = [UIImage imageWithCGImage:newCgImg];
1990 CGImageRelease(newCgImg);
1991
1992 // Save the image in both PNG and JPEG formats
1993 // The contextDescription now should indicate the desired format
1994 saveFuzzedImage(newImage, @"premultiplied_first_alpha_png");
1995 saveFuzzedImage(newImage, @"premultiplied_first_alpha_jpeg");
1996 saveFuzzedImage(newImage, @"premultiplied_first_alpha_gif");
1997
1998 NSLog(@"Modified UIImage created and saved successfully in both PNG and JPEG formats.");
1999 }
2000
2001 CGContextRelease(ctx);
2002 free(rawData);
2003}

References applyEnhancedFuzzingToBitmapContext(), and saveFuzzedImage().

Referenced by processImage().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ createBitmapContextStandardRGB()

void createBitmapContextStandardRGB ( CGImageRef cgImg,
int permutation )

Creates a bitmap context with standard RGB settings, applies a fuzzing process to alter the image, and saves the fuzzed image. Useful for testing image processing functionalities or creating varied visual effects.

This function demonstrates how to create a bitmap context, manipulate image pixel data through a fuzzing process, and save the modified image. It covers validating input images, creating bitmap contexts with specific configurations, and applying image processing algorithms to explore and enhance image processing techniques.

Parameters
cgImgThe source image from which to create the bitmap context, represented as a CGImageRef.
permutationAn integer representing the type or level of fuzzing to apply. Though not utilized in this simplified example, it is designed to dictate different fuzzing algorithms or intensities.
Note
  • Memory Management: Demonstrates careful release of resources, including color space and bitmap context, and freeing of dynamically allocated memory.
  • Debugging: Includes commented-out calls to debugMemoryHandling to illustrate potential insertion points for memory diagnostics.
  • Extensibility: The permutation parameter demonstrates the function's potential to apply various fuzzing types based on input parameters, enhancing modularity and maintainability.
  • Logging: Utilizes NSLog for debugging purposes. A more sophisticated logging framework is recommended for production code.
  • Separation of Concerns: Abstracts the actual fuzzing logic into the applyEnhancedFuzzingToBitmapContext function, promoting code modularity and maintainability.

Process Overview:

  1. Validates the CGImageRef input to ensure a source image is provided.
  2. Retrieves source image dimensions and calculates bytes per row for an RGBA pixel format.
  3. Allocates memory for raw pixel data.
  4. Creates a CGColorSpaceRef in the device RGB color space.
  5. Specifies bitmap information for alpha channel handling and byte order.
  6. Creates the bitmap context with allocated memory, color space, and specified bitmap info.
  7. Draws the source image into the bitmap context.
  8. Applies a fuzzing algorithm to manipulate the pixel data directly.
  9. Generates a new CGImageRef from the bitmap context, converts it to UIImage, and saves the result.
  10. Releases allocated resources, including the bitmap context and pixel data memory.

Usage Example:

// Process with all configurations
processImage(myImage, -1);
// Process with a specific configuration
processImage(myImage, 3); // Example: Applies Non-Premultiplied Alpha settings

Definition at line 1813 of file xnuimagefuzzer.m.

1813 {
1814 NSLog(@"Creating bitmap context with Standard RGB settings and applying fuzzing");
1815// debugMemoryHandling();
1816
1817 if (!cgImg) {
1818 NSLog(@"Invalid CGImageRef provided.");
1819 return;
1820 }
1821
1822 size_t width = CGImageGetWidth(cgImg);
1823 size_t height = CGImageGetHeight(cgImg);
1824 size_t bytesPerRow = width * 4; // 4 bytes per pixel (RGBA)
1825
1826 unsigned char *rawData = (unsigned char *)calloc(height * bytesPerRow, sizeof(unsigned char));
1827 if (!rawData) {
1828 NSLog(@"Failed to allocate memory for image processing");
1829// debugMemoryHandling();
1830 return;
1831 }
1832
1833 CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
1834 if (!colorSpace) {
1835 NSLog(@"Failed to create color space");
1836 free(rawData);
1837// debugMemoryHandling();
1838 return;
1839 }
1840
1841 CGBitmapInfo bitmapInfo = kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big;
1842 CGContextRef ctx = CGBitmapContextCreate(rawData, width, height, 8, bytesPerRow, colorSpace, bitmapInfo);
1843
1844 CGColorSpaceRelease(colorSpace);
1845
1846 if (!ctx) {
1847 NSLog(@"Failed to create bitmap context");
1848 free(rawData);
1849// debugMemoryHandling();
1850 return;
1851 }
1852
1853 CGContextDrawImage(ctx, CGRectMake(0, 0, width, height), cgImg);
1854
1855 NSLog(@"Applying enhanced fuzzing logic to the bitmap context");
1856 applyEnhancedFuzzingToBitmapContext(rawData, width, height, verboseLogging);
1857 // Initialize a variable to keep track of unchanged and changed bytes
1858 size_t unchangedCount = 0;
1859 size_t changedCount = 0;
1860
1861 // Check for 0x41 pattern after operations and detect changes
1862 for (size_t i = 0; i < height * bytesPerRow; i++) {
1863 if (rawData[i] == 0x41) {
1864 unchangedCount++;
1865 } else {
1866 // Log the first few changes to avoid flooding the log
1867 if (changedCount < 10) { // Limiting to the first 10 changes for brevity
1868 NSLog(@"Detected change from 0x41 at byte offset %zu, new value: 0x%X", i, rawData[i]);
1869 }
1870 changedCount++;
1871 }
1872 }
1873
1874 // Summarize findings
1875 if (unchangedCount > 0) {
1876 NSLog(@"Detected unchanged 0x41 pattern in %zu places.", unchangedCount);
1877 }
1878 NSLog(@"Detected changes in %zu places.", changedCount);
1879
1880 CGImageRef newCgImg = CGBitmapContextCreateImage(ctx);
1881 if (!newCgImg) {
1882 NSLog(@"Failed to create CGImage from context");
1883 } else {
1884 UIImage *newImage = [UIImage imageWithCGImage:newCgImg];
1885 CGImageRelease(newCgImg);
1886
1887 saveFuzzedImage(newImage, @"premultiplied_first_alpha_png");
1888 saveFuzzedImage(newImage, @"premultiplied_first_alpha_jpeg");
1889 saveFuzzedImage(newImage, @"premultiplied_first_alpha_gif");
1890
1891 NSLog(@"Modified UIImage created and saved successfully.");
1892 }
1893
1894 CGContextRelease(ctx);
1895 free(rawData);
1896// debugMemoryHandling();
1897}

References applyEnhancedFuzzingToBitmapContext(), saveFuzzedImage(), and verboseLogging.

Referenced by processImage().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ createUniqueDirectoryForSavingImages()

NSString * createUniqueDirectoryForSavingImages ( void )

Creates a unique directory for saving images within the documents directory.

Generates a unique directory name by combining the current date-time stamp and a random component, ensuring uniqueness. This directory is created within the application's documents directory, intended for storing processed images. Useful in scenarios requiring organized storage without naming conflicts, maintaining chronological order. The inclusion of a random component further ensures directory name uniqueness, even when created in rapid succession.

Returns
The path to the newly created unique directory, or nil if an error occurred. This path can be used directly to save files within the new directory.

Definition at line 817 of file xnuimagefuzzer.m.

817 {
818 // Initialize date formatter for timestamp
819 NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
820 formatter.dateFormat = @"yyyy-MM-dd_HH-mm-ss-SSS";
821
822 // Generate unique directory name with current date-time and a random component
823 NSString *dateString = [formatter stringFromDate:[NSDate date]];
824 uint32_t randomComponent = arc4random_uniform(10000); // Ensures additional uniqueness
825 NSString *uniqueDirectoryName = [NSString stringWithFormat:@"%@_%u", dateString, randomComponent];
826
827 // Retrieve path to the documents directory
828 NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
829
830 // Construct the path for the new unique directory
831 NSString *uniqueDirPath = [documentsDirectory stringByAppendingPathComponent:uniqueDirectoryName];
832
833 // Attempt to create the directory
834 NSError *error = nil;
835 if (![[NSFileManager defaultManager] createDirectoryAtPath:uniqueDirPath withIntermediateDirectories:YES attributes:nil error:&error]) {
836 NSLog(@"Error creating directory for saving images: %@", error.localizedDescription);
837 return nil; // Return nil in case of failure
838 }
839
840 // Return the path of the successfully created directory
841 return uniqueDirPath;
842}

◆ debugMemoryHandling()

void debugMemoryHandling ( void )

Allocates and deallocates memory chunks using mmap and munmap for debugging.

This function facilitates memory handling debugging by allocating and then deallocating a predetermined number of memory chunks. It utilizes the mmap and munmap system calls, offering a lower-level look at memory management beyond what high-level languages typically provide. This approach is useful for examining application behavior under various memory conditions and demonstrating memory mapping techniques.

  • Allocation: Allocates 64 chunks of memory, each 64 KB in size, using the MAP_ANONYMOUS and MAP_PRIVATE flags with mmap, simulating a scenario where memory is used but not backed by any file.
  • Initialization: Each allocated chunk is filled with the byte 0x41 ('A'), which can help in identifying how memory content changes over time or remains unaltered after certain operations.
  • Deallocation: Utilizes munmap to free each allocated chunk, ensuring no memory leaks and providing a clean state post-execution.
Note
This function is instrumental for developers looking to understand or teach memory management intricacies, debug memory allocation issues, or test how their applications respond to specific memory usage patterns. It logs the address of each allocated and subsequently deallocated chunk, enhancing transparency in memory management operations.

Example Usage:

// Call debugMemoryHandling to observe memory allocation and deallocation behavior
// Output will include the address of allocated memory chunks and confirmation of their deallocation
void debugMemoryHandling(void)
Allocates and deallocates memory chunks using mmap and munmap for debugging.
  • The use of NSLog for logging makes this function readily applicable in macOS or iOS development environments. However, the logging mechanism can be adapted for use in other environments as needed.
  • The chosen memory chunk size (0x10000 bytes) and the number of chunks (64) can be modified to suit different debugging needs or to test application behavior under various memory load scenarios.

Definition at line 1333 of file xnuimagefuzzer.m.

1333 {
1334 const size_t sz = 0x10000;
1335 char* chunks[64] = { NULL };
1336 for (int i = 0; i < 64; i++) {
1337 char* chunk = (char *)mmap(0, sz, PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_PRIVATE, -1, 0);
1338 if (chunk == MAP_FAILED) {
1339 NSLog(@"Failed to map memory for chunk %d", i);
1340 continue;
1341 }
1342 memset(chunk, 0x41, sz);
1343 NSLog(@"Chunk @ %p", chunk);
1344 chunks[i] = chunk;
1345 }
1346
1347 for (int i = 0; i < 64; i++) {
1348 if (chunks[i] != NULL) {
1349 if (munmap(chunks[i], sz) == -1) {
1350 NSLog(@"Failed to unmap chunk @ %p", chunks[i]);
1351 } else {
1352 NSLog(@"Successfully unmapped chunk @ %p", chunks[i]);
1353 }
1354 }
1355 }
1356}

◆ dump_comm_page()

void dump_comm_page ( void )

Definition at line 502 of file xnuimagefuzzer.m.

502 {
503 char *sig = signature();
504 if (sig) {
505 NSLog(@"[*] COMM_PAGE_SIGNATURE: %s", sig);
506 free(sig);
507 } else {
508 NSLog(@"[*] COMM_PAGE_SIGNATURE: Error reading signature.");
509 }
510
511 // Utilizing macro for simplified reading
512 NSLog(@"[*] COMM_PAGE_VERSION: %d", READ_COMM_PAGE_VALUE(uint16_t, COMM_PAGE64_BASE_ADDRESS + 0x01E));
513 NSLog(@"[*] COMM_PAGE_NCPUS: %d", READ_COMM_PAGE_VALUE(uint8_t, COMM_PAGE64_BASE_ADDRESS + 0x022));
514 // Additional comm page details could be added here
515
516 NSLog(@"[*] COMM_PAGE_CPU_CAPABILITIES64:");
517 uint64_t cpu_caps = READ_COMM_PAGE_VALUE(uint64_t, COMM_PAGE_CPU_CAPABILITIES64);
518 for (int i = 0, shift = 0; i < (int)(sizeof(cpu_cap_strings) / sizeof(char *)); i++) {
519 if (i == 16) { // Special handling for NumCPUs
520 NSLog(@"\t%s: %d", cpu_cap_strings[i], (int)(cpu_caps >> 16) & 0xFF);
521 shift = 24; // Skip to the next relevant bit
522 continue;
523 }
524 NSLog(@"\t%s: %@", cpu_cap_strings[i], (cpu_caps & (1ULL << shift)) ? @"true" : @"false");
525 shift++;
526 }
527 NSLog(@"[*] Done dumping comm page.");
528}
#define READ_COMM_PAGE_VALUE(type, address)
Dumps key communication page details for diagnostic purposes.
char * signature(void)
const char * cpu_cap_strings[]
Identifies the CPU's supported capabilities.

References COMM_PAGE64_BASE_ADDRESS, COMM_PAGE_CPU_CAPABILITIES64, cpu_cap_strings, READ_COMM_PAGE_VALUE, and signature().

Referenced by main().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ dumpDeviceInfo()

void dumpDeviceInfo ( void )

Logs comprehensive information about the current device.

This utility function leverages the UIDevice class to access and log a wide range of information about the device on which the application is running. It covers basic device identifiers, operating system details, and battery status, providing a holistic view of the device's configuration and state.

The function temporarily enables battery monitoring to retrieve the current battery level and state, supplementing the device information with power status. This could be particularly useful for applications that need to adjust their behavior or performance based on the device's power status.

Warning
Battery information is specific to iOS and iPadOS devices and might not reflect real-time changes accurately due to system optimizations and power management.
void dumpDeviceInfo(void)
Logs comprehensive information about the current device.

This example demonstrates how to call dumpDeviceInfo to log device information. This can be particularly useful during development and debugging to understand the environment in which the application is operating.

Note
Ensure that you check the device's capability to provide battery information and handle any potential inaccuracies in the reported levels and states. Consider the privacy implications of logging and handling the unique identifier for the vendor (identifierForVendor).
See also
UIDevice for detailed documentation on accessing device properties.

Definition at line 344 of file xnuimagefuzzer.m.

344 {
345UIDevice *device = [UIDevice currentDevice];
346NSLog(@"Device Information:");
347NSLog(@" Name: %@", device.name);
348NSLog(@" Model: %@", device.model);
349NSLog(@" System Name: %@", device.systemName);
350NSLog(@" System Version: %@", device.systemVersion);
351NSLog(@" Identifier For Vendor: %@", device.identifierForVendor.UUIDString);
352
353device.batteryMonitoringEnabled = YES; // Enable battery monitoring
354NSLog(@" Battery Level: %f", device.batteryLevel * 100); // Convert to percentage
355NSString *batteryState;
356switch (device.batteryState) {
357 case UIDeviceBatteryStateUnknown:
358 batteryState = @"Unknown";
359 break;
360 case UIDeviceBatteryStateUnplugged:
361 batteryState = @"Unplugged";
362 break;
363 case UIDeviceBatteryStateCharging:
364 batteryState = @"Charging";
365 break;
366 case UIDeviceBatteryStateFull:
367 batteryState = @"Full";
368 break;
369 default:
370 batteryState = @"Not Available";
371 break;
372}
373NSLog(@" Battery State: %@", batteryState);
374device.batteryMonitoringEnabled = NO; // Disable battery monitoring after fetching information
375}

Referenced by main().

+ Here is the caller graph for this function:

◆ dumpMacDeviceInfo()

void dumpMacDeviceInfo ( void )

Logs system information for macOS devices.

This function is specifically designed to fetch and log key pieces of system information for macOS devices, utilizing the sysctl interface. It provides insights into the kernel version, hardware model, and CPU type, among others, offering a clear snapshot of the underlying hardware and operating system specifics.

Key Information Retrieved:

  • Kernel Version: The version of the Darwin kernel the system is running.
  • Hardware Model: The specific model of the macOS device, useful for identifying hardware capabilities.
  • CPU Type: Details about the CPU, including its brand and specifications, which can inform performance expectations and compatibility.

Usage:

This function is tailor-made for macOS environments and can be invoked directly to log the system information to the console:

void dumpMacDeviceInfo(void)
Logs system information for macOS devices.

Example Output:

System Information:
Kernel Version: Darwin 20.3.0
Hardware Model: MacBookPro15,1
CPU Type: Intel(R) Core(TM) i7-9750H CPU @ 2.60GHz
Note
While this function is designed with macOS in mind, accessing system information via sysctl is a method that could potentially be adapted for other Unix-like systems with appropriate modifications.
See also
For more in-depth details on using sysctl, refer to the man pages (man sysctl) or the official documentation for the sysctl interface.

Definition at line 407 of file xnuimagefuzzer.m.

407 {
408 char str[128];
409 size_t size = sizeof(str);
410
411 // Query and log the kernel version
412 sysctlbyname("kern.osrelease", str, &size, NULL, 0);
413 NSLog(@"Kernel Version: %s", str);
414
415 // Reset size for the next sysctlbyname call
416 size = sizeof(str);
417 // Query and log the hardware model
418 sysctlbyname("hw.model", str, &size, NULL, 0);
419 NSLog(@"Hardware Model: %s", str);
420
421 // Reset size for the next sysctlbyname call
422 size = sizeof(str);
423 // Query and log the CPU type
424 sysctlbyname("machdep.cpu.brand_string", str, &size, NULL, 0);
425 NSLog(@"CPU Type: %s", str);
426
427}

Referenced by main().

+ Here is the caller graph for this function:

◆ formattedCurrentDateTime()

NSString * formattedCurrentDateTime ( void )
Examples
/Users/xss/Developer/xnuimagefuzzer/XNU Image Fuzzer/xnuimagefuzzer.m.

Definition at line 266 of file xnuimagefuzzer.m.

266 {
267 NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
268 [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
269 NSString *formattedDate = [dateFormatter stringFromDate:[NSDate date]];
270 return formattedDate;
271}

Referenced by main().

+ Here is the caller graph for this function:

◆ generateFuzzedImageData()

NSData * generateFuzzedImageData ( size_t width,
size_t height,
CFStringRef imageType )

Generates a random image for fuzzing.

This function creates a random image with specified width, height, and type, fills it with random data, and returns the generated image data.

  • Parameters:
    • width: The width of the generated image.
    • height: The height of the generated image.
    • imageType: The type of the generated image (e.g., PNG, JPEG).
  • Image Data: Allocates a buffer and fills it with random data.
  • Graphics Context: Creates a bitmap graphics context and generates an image.
  • Image Destination: Adds the image to a destination and finalizes it.
Parameters
widthThe width of the generated image.
heightThe height of the generated image.
imageTypeThe type of the generated image.
Returns
NSData containing the generated image data.

Definition at line 1446 of file xnuimagefuzzer.m.

1446 {
1447 size_t bytesPerPixel = 4; // Assuming RGBA
1448 size_t bitsPerComponent = 8;
1449 size_t bytesPerRow = width * bytesPerPixel;
1450 size_t bufferSize = bytesPerRow * height;
1451
1452 uint8_t *buffer = (uint8_t *)malloc(bufferSize);
1453 for (size_t i = 0; i < bufferSize; i++) {
1454 buffer[i] = arc4random_uniform(256);
1455 }
1456
1457 CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
1458 CGContextRef context = CGBitmapContextCreate(buffer, width, height, bitsPerComponent, bytesPerRow, colorSpace, kCGImageAlphaPremultipliedLast);
1459 CGImageRef imageRef = CGBitmapContextCreateImage(context);
1460
1461 NSMutableData *imageData = [NSMutableData data];
1462 CGImageDestinationRef destination = CGImageDestinationCreateWithData((CFMutableDataRef)imageData, imageType, 1, NULL);
1463 CGImageDestinationAddImage(destination, imageRef, NULL);
1464 CGImageDestinationFinalize(destination);
1465
1466 CGColorSpaceRelease(colorSpace);
1467 CGContextRelease(context);
1468 CGImageRelease(imageRef);
1469 CFRelease(destination);
1470 free(buffer);
1471
1472 return imageData;
1473}

Referenced by performAllImagePermutations().

+ Here is the caller graph for this function:

◆ hashString()

unsigned long hashString ( const char * str)

Computes a hash value for a given string.

This function implements the djb2 algorithm, a simple and effective hash function for strings. The algorithm iterates over each character in the input string, combining the previous hash value and the current character to produce a new hash. This method is known for its simplicity and decent distribution properties, making it suitable for a variety of hashing needs where extreme cryptographic security is not required.

Parameters
strPointer to the input string to be hashed. The string is assumed to be null-terminated.
Returns
Returns an unsigned long representing the hash value of the input string.
Note
The hash value is computed using a specific formula: hash * 33 + c, where hash is the current hash value, and c is the ASCII value of the current character. This formula is applied iteratively over each character of the string, starting with an initial hash value of 5381, which is a commonly used starting point for the djb2 algorithm.

Definition at line 1371 of file xnuimagefuzzer.m.

1371 {
1372 unsigned long hash = 5381; // Initial value for djb2 algorithm
1373 int c;
1374
1375 // Iteratively compute the hash value for each character
1376 while ((c = *str++)) {
1377 hash = ((hash << 5) + hash) + c; // hash * 33 + c
1378 }
1379
1380 return hash; // Return the computed hash value
1381}

Referenced by applyEnhancedFuzzingToBitmapContextWithFloats().

+ Here is the caller graph for this function:

◆ invertColor()

void invertColor ( float * pixel)

◆ isValidImagePath()

BOOL isValidImagePath ( NSString * path)

Prototypes for utility functions used in image processing.

Validates the existence of a file at a specified path.

This section declares functions essential for the image processing pipeline, ranging from path validation to image manipulation and utility operations. These functions facilitate tasks such as validating image paths, loading images from files, applying various image processing permutations, and managing output directories and string hashing.

  • isValidImagePath: Validates the specified image path.
  • loadImageFromFile: Loads an image from the given file path.
  • processImage: Processes the image with a specified permutation algorithm.
  • Additional utilities include noise application, color inversion, value adjustments, and string hashing.
Returns
Various return types depending on the function's purpose.
Note
Some functions, such as processImage, might modify the input image directly.

Checks if an image file exists at a given path, essential for applications that require the presence of a file before performing further operations. Utilizes NSFileManager's fileExistsAtPath: to assess file presence, ensuring the path's validity for subsequent processing or operations. This function is crucial in contexts where the accuracy of file paths directly impacts application behavior or user experience.

Parameters
pathNSString representing the file path to validate.
Returns
Returns YES if the file exists at the specified path; otherwise, returns NO.
Note
  • Implementation: Leverages NSFileManager for reliable file existence checks. Logs the outcome to provide clear feedback on path validity.
  • Versatility: While demonstrated for image files, this method can be adapted for any file type, enhancing its utility across various application needs.

Example Usage:

BOOL valid = isImagePathValid(@"/path/to/image.png");
if (valid) {
NSLog(@"The image path is valid. Proceed with loading or processing.");
} else {
NSLog(@"The image path is invalid. Check the path or notify the user.");
}

Definition at line 1574 of file xnuimagefuzzer.m.

1574 {
1575 BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:path];
1576 NSLog(fileExists ? @"Valid image path: %@" : @"Invalid image path: %@", path);
1577 return fileExists;
1578}

◆ loadImageFromFile()

UIImage * loadImageFromFile ( NSString * imageName)

Loads an image from the application bundle into a UIImage object.

Essential for iOS applications, this function loads images stored within the app's resources, facilitating the display or processing of those images. It abstracts filesystem complexities, allowing developers to concentrate on resource utilization.

Parameters
imageNameNSString representing the file name (including its extension) of the image to load.
Returns
A UIImage object initialized with the specified image file's contents or nil if the image could not be loaded.
Note
  • Path Retrieval: Uses NSBundle's pathForResource:ofType: to locate the image file, simplifying access to app resources.
  • Data Conversion: Converts the file content into NSData, a format compatible with UIImage's imageWithData: initializer.
  • UIImage Initialization: Creates a UIImage from NSData. On success, logs image details like dimensions and scale for debugging or information.

Example Usage:

UIImage *loadedImage = loadImageFromFile(@"exampleImage.png");
if (loadedImage) {
NSLog(@"Image loaded successfully with dimensions: %f x %f", loadedImage.size.width, loadedImage.size.height);
} else {
NSLog(@"Failed to load image.");
}
UIImage * loadImageFromFile(NSString *path)
Loads an image from the application bundle into a UIImage object.

Definition at line 1605 of file xnuimagefuzzer.m.

1605 {
1606 NSLog(@"Loading file: %@", imageName);
1607 NSString *imagePath = [[NSBundle mainBundle] pathForResource:imageName ofType:nil];
1608 if (!imagePath) {
1609 NSLog(@"Failed to find path for image: %@", imageName);
1610 return nil;
1611 }
1612 NSLog(@"Image path: %@", imagePath);
1613
1614 NSData *content = [NSData dataWithContentsOfFile:imagePath];
1615 if (!content) {
1616 NSLog(@"Failed to load data from file: %@", imagePath);
1617 return nil;
1618 }
1619
1620 UIImage *image = [UIImage imageWithData:content];
1621 if (!image) {
1622 NSLog(@"Failed to create UIImage from data.");
1623 return nil;
1624 }
1625
1626 NSLog(@"UIImage created: %@, Size: {width: %.2f, height: %.2f}, Scale: %f, Orientation: %ld",
1627 image, image.size.width, image.size.height, image.scale, (long)image.imageOrientation);
1628
1629 return image;
1630}

Referenced by main().

+ Here is the caller graph for this function:

◆ logPixelData()

void logPixelData ( unsigned char * rawData,
size_t width,
size_t height,
const char * message,
BOOL verboseLogging )

Logs information about a random set of pixels from an image's raw data.

Selects a random set of pixels from the provided image data and logs their RGBA components. If verbose logging is enabled, it decodes and logs character data embedded within the pixel values, providing insights into the image's content or image processing results. Assumes RGBA format for pixel data.

Parameters
rawDataThe raw pixel data of the image.
widthThe width of the image in pixels.
heightThe height of the image in pixels.
messageA contextual message or identifier for the log.
verboseLoggingEnables detailed information logging, including decoded data, when set to true.
Note
Ensure the provided raw data correctly corresponds to the specified width and height to avoid out-of-bounds access.

Definition at line 863 of file xnuimagefuzzer.m.

863 {
864 if (!rawData || width == 0 || height == 0) {
865 NSLog(@"%s - Invalid data or dimensions. Logging aborted.", message);
866 return;
867 }
868
869 const int numberOfPixelsToLog = 5; // Number of random pixels to log
870
871 NSLog(@"%s - %s logging %d random pixels:", message, verboseLogging ? "Verbose" : "Basic", numberOfPixelsToLog);
872
873 for (int i = 0; i < numberOfPixelsToLog; i++) {
874 unsigned int randomX = arc4random_uniform((unsigned int)width);
875 unsigned int randomY = arc4random_uniform((unsigned int)height);
876 size_t pixelIndex = (randomY * width + randomX) * 4; // Index for RGBA
877
878 if (pixelIndex + 3 < width * height * 4) {
879 unsigned char r = rawData[pixelIndex];
880 unsigned char g = rawData[pixelIndex + 1];
881 unsigned char b = rawData[pixelIndex + 2];
882 unsigned char a = rawData[pixelIndex + 3];
883
884 NSLog(@"%s - Pixel[%u, %u]: R=%u, G=%u, B=%u, A=%u", message, randomX, randomY, r, g, b, a);
885
886 if (verboseLogging) {
887 // Decoding embedded character data from pixel values as an example
888 unsigned char decodedChar = (r & 1) | ((g & 1) << 1) | ((b & 1) << 2);
889 NSLog(@"%s - Decoded data from Pixel[%u, %u]: %c", message, randomX, randomY, decodedChar);
890 }
891 } else {
892 NSLog(@"%s - Out of bounds pixel access prevented at [%u, %u].", message, randomX, randomY);
893 }
894 }
895}

References verboseLogging.

◆ LogRandomPixelData()

void LogRandomPixelData ( unsigned char * rawData,
size_t width,
size_t height,
const char * message )

Logs information about a random set of pixels from an image's raw data.

This function is designed to offer a quick diagnostic look at the content of an image by logging the color values of a randomly selected set of pixels. It's particularly useful for debugging and for verifying the effects of image processing algorithms. By providing a message or identifier, developers can contextualize the log output, making it easier to track logs related to specific images or operations. The function provides a high-level overview of pixel data without detailed analysis or decoding.

Parameters
rawDataThe raw pixel data of the image. This should be a pointer to the start of the pixel data array.
widthThe width of the image in pixels. This is used to calculate the position of pixels within the raw data array.
heightThe height of the image in pixels. Along with width, this determines the total number of pixels that can be logged.
messageA message or identifier to include in the log for context. This helps to identify the log output related to specific images or processing steps.

Definition at line 908 of file xnuimagefuzzer.m.

908 {
909 if (!rawData || width == 0 || height == 0) {
910 NSLog(@"%s - Invalid data or dimensions. Logging aborted.", message);
911 return;
912 }
913
914 const int numberOfPixelsToLog = 5; // Number of random pixels to log
915 NSLog(@"%s - Logging %d random pixels:", message, numberOfPixelsToLog);
916
917 for (int i = 0; i < numberOfPixelsToLog; i++) {
918 unsigned int randomX = arc4random_uniform((unsigned int)width);
919 unsigned int randomY = arc4random_uniform((unsigned int)height);
920 size_t pixelIndex = (randomY * width + randomX) * 4; // Assumes 4 bytes per pixel (RGBA)
921
922 if (pixelIndex + 3 < width * height * 4) {
923 NSLog(@"%s - Pixel[%u, %u]: R=%d, G=%d, B=%d, A=%d",
924 message, randomX, randomY,
925 rawData[pixelIndex], rawData[pixelIndex + 1],
926 rawData[pixelIndex + 2], rawData[pixelIndex + 3]);
927 } else {
928 NSLog(@"%s - Out of bounds pixel access prevented at [%u, %u].", message, randomX, randomY);
929 }
930 }
931}

◆ main()

int main ( int argc,
const char * argv[] )

Entry point of the application, handling initialization, argument parsing, and image processing.

Sets up the application environment, parses command-line arguments for image loading and processing, and manages resources efficiently. Demonstrates a command-line utility pattern in Objective-C, integrating C and Objective-C elements for image processing tasks.

  • Environment Variables Setup: Configures variables for detailed logging and debugging.
  • Command-Line Arguments: Validates and parses arguments for image processing.
  • Image Processing: Loads and processes the specified image.
Parameters
argcCount of command-line arguments.
argvArray of command-line arguments.
Returns
Returns 0 on success, 1 on failure.
Note
Utilizes @autoreleasepool for efficient memory management. The initial environment variable configurations are for debugging and may need adjustment depending on deployment.

Definition at line 1497 of file xnuimagefuzzer.m.

1497 {
1498 @autoreleasepool {
1499 // Initial log with timestamp
1500 NSString *currentTime = formattedCurrentDateTime();
1501 NSLog(@"XNU Image Fuzzer starting %@", currentTime);
1502
1503 // Set environment variables for detailed logging and debugging
1504 const char *envVars[] = {
1505 "CGBITMAP_CONTEXT_LOG_ERRORS", "CG_PDF_VERBOSE", "CG_CONTEXT_SHOW_BACKTRACE",
1506 "CG_CONTEXT_SHOW_BACKTRACE_ON_ERROR", "CG_IMAGE_SHOW_MALLOC", "CG_LAYER_SHOW_BACKTRACE",
1507 "CGBITMAP_CONTEXT_LOG", "CGCOLORDATAPROVIDER_VERBOSE", "CGPDF_LOG_PAGES",
1508 "MALLOC_CHECK_", "NSZombieEnabled", "NSAssertsEnabled", "NSShowAllViews",
1509 "IDELogRedirectionPolicy"
1510 };
1511 const char *envValues[] = {
1512 "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "YES", "YES", "YES", "oslogToStdio"
1513 };
1514 for (int i = 0; i < sizeof(envVars) / sizeof(char *); i++) {
1515 setenv(envVars[i], envValues[i], 1);
1516 }
1517
1518 // Detect if launched with user-provided command-line arguments for image processing
1519 if (argc > 2 && argv[1][0] != '-') {
1520 NSString *imageName = [NSString stringWithUTF8String:argv[1]];
1521 int permutation = atoi(argv[2]);
1522
1523 NSLog(@"Loading file: %@", imageName);
1524 UIImage *image = loadImageFromFile(imageName);
1525 if (!image) {
1526 NSLog(@"Failed to find path for image: %@", imageName);
1527 NSLog(@"Failed to load image: %@", imageName);
1528 return 1; // Error due to failed image loading
1529 }
1530
1531 processImage(image, permutation);
1535
1536 NSLog(@"XNU Image Fuzzer ✅ %@", currentTime);
1537 return 0; // Successful completion of command-line image processing
1538 } else if (argc == 1 || (argc > 2 && argv[1][0] == '-')) {
1539 // Perform all image permutations if no valid user-provided arguments are present
1541 return 0; // Successful completion of image permutation fuzzing
1542 } else {
1543 NSLog(@"Incorrect usage. Expected 0 or 2 arguments, got %d", argc - 1);
1544 NSLog(@"Usage: %s <imagePath> <permutation>", argv[0]);
1545 return 1; // Error due to incorrect usage
1546 }
1547 }
1548}
void performAllImagePermutations(void)
Generates a random image and processes it with all permutation strategies.
NSString * formattedCurrentDateTime(void)

References dump_comm_page(), dumpDeviceInfo(), dumpMacDeviceInfo(), formattedCurrentDateTime(), loadImageFromFile(), performAllImagePermutations(), and processImage().

+ Here is the call graph for this function:

◆ performAllImagePermutations()

void performAllImagePermutations ( void )

Generates a random image and processes it with all permutation strategies.

This function defines the dimensions and image type for a generated image, creates the image data, writes it to a temporary file, loads the image, and processes it with permutation -1, indicating all permutations.

  • Image Generation: Creates a random image with specified dimensions and type.
  • File Handling: Writes the generated image data to a temporary file.
  • Image Loading: Loads the generated image from the file.
  • Image Processing: Processes the image with all permutations.
Note
This function is used when no command-line arguments are provided to automatically generate and process an image.

Definition at line 1402 of file xnuimagefuzzer.m.

1402 {
1403 // Define dimensions and image type for the generated image
1404 size_t width = 128;
1405 size_t height = 128;
1406 CFStringRef imageType = (__bridge CFStringRef)UTTypePNG.identifier;
1407
1408 // Generate the fuzzed image data
1409 NSData *fuzzedImage = generateFuzzedImageData(width, height, imageType);
1410 NSString *path = @"/tmp/fuzzed_image.png";
1411 [fuzzedImage writeToFile:path atomically:YES];
1412
1413 // Load the generated image
1414 UIImage *image = [UIImage imageWithData:fuzzedImage];
1415 if (!image) {
1416 NSLog(@"Failed to load generated image from path: %@", path);
1417 return;
1418 }
1419
1420 // Process the image with permutation -1 (all permutations)
1421 processImage(image, -1);
1422}
NSData * generateFuzzedImageData(size_t width, size_t height, CFStringRef imageType)
Generates a random image for fuzzing.

References generateFuzzedImageData(), and processImage().

Referenced by main().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ printColored()

void printColored ( const char * color,
const char * message )

Prints a message with specified ANSI color to the console.

This utility function enhances console log visibility by allowing messages to be printed in different colors. It wraps a provided message with the specified ANSI color code, ensuring the message stands out in the console output. After printing the message, it resets the console color back to its default, maintaining the terminal's readability for subsequent outputs.

Parameters
colorThe ANSI color code that dictates the color of the message. This parameter expects a string representation of ANSI color codes (e.g., "\033[31m" for red).
messageThe text message to be printed. This string is the content that will be displayed in the specified color in the console.
Note
This function relies on the terminal or console's support for ANSI color codes. If the terminal does not support these codes, the message will be printed without color formatting, and escape codes may be visible.

Example Usage:

printColored("\033[31m", "Error: File not found.");
void printColored(const char *color, const char *message)
Prints a message with specified ANSI color to the console.

This example demonstrates how to use the printColored function to print an error message in red, making it more noticeable in the console output.

See Also: ANSI color codes documentation for more information on how colors are represented in terminals.

Definition at line 552 of file xnuimagefuzzer.m.

552 {
553 NSLog(@"%s%s%s", color, message, RESET_COLOR);
554}
#define RESET_COLOR

References RESET_COLOR.

◆ processImage()

void processImage ( UIImage * image,
int permutation )

Processes an image using various bitmap context configurations.

Central to testing different bitmap context configurations, this function allows for the exploration and application of a wide range of image processing techniques. Configurations vary by color space, alpha settings, bit depth, and pixel format, enabling comprehensive testing across different image processing scenarios.

Parameters
imageThe UIImage object to be processed, which must contain a valid CGImage.
permutationAn integer specifying the bitmap context configuration to apply. A value of -1 applies all configurations in a loop, while any other value selects a specific configuration.
Note
  • CGImage Retrieval: Begins by extracting the CGImage from the UIImage. Logs an error and exits if this step fails.
  • Configuration Application: Iterates through or selects a specific bitmap context configuration to apply. Logs each action and utilizes corresponding functions for creating and processing the bitmap context.
  • Modular Processing Logic: Processing for each configuration is handled in separate functions, facilitating easy adjustments or expansions to processing capabilities.

Usage Example:

// Process with all configurations
processImage(myImage, -1);
// Process with a specific configuration
processImage(myImage, 3); // Example: Applies Non-Premultiplied Alpha settings

Definition at line 1655 of file xnuimagefuzzer.m.

1655 {
1656 CGImageRef cgImg = [image CGImage];
1657 if (!cgImg) {
1658 NSLog(@"Failed to get CGImage from UIImage.");
1659 return;
1660 }
1661 NSLog(@"CGImage created from UIImage. Dimensions: %zu x %zu", CGImageGetWidth(cgImg), CGImageGetHeight(cgImg));
1662
1663 if (permutation == -1) {
1664 for (int i = 1; i <= 12; i++) {
1665 switch (i) {
1666 case 1:
1667 NSLog(@"Case: Creating bitmap context with Standard RGB settings");
1668 createBitmapContextStandardRGB(cgImg, permutation);
1669 break;
1670 case 2:
1671 NSLog(@"Case: Creating bitmap context with Premultiplied First Alpha settings");
1673 break;
1674 case 3:
1675 NSLog(@"Case: Creating bitmap context with Non-Premultiplied Alpha settings");
1677 break;
1678 case 4:
1679 NSLog(@"Case: Creating bitmap context with 16-bit depth settings");
1681 break;
1682 case 5:
1683 NSLog(@"Grayscale image processing is currently pending implementation.");
1684 break;
1685 case 6:
1686 NSLog(@"Case: Creating bitmap context with HDR Float Components settings");
1688 break;
1689 case 7:
1690 NSLog(@"Case: Creating bitmap context with Alpha Only settings");
1692 break;
1693 case 8:
1694 NSLog(@"Case: Creating bitmap context with 1-bit Monochrome settings");
1696 break;
1697 case 9:
1698 NSLog(@"Case: Creating bitmap context with Big Endian pixel format settings");
1700 break;
1701 case 10:
1702 NSLog(@"Case: Creating bitmap context with Little Endian pixel format settings");
1704 break;
1705 case 11:
1706 NSLog(@"Case: Creating bitmap context with 8-bit depth, inverted colors settings");
1708 break;
1709 case 12:
1710 NSLog(@"Case: Creating bitmap context with 32-bit float, 4-component settings");
1712 break;
1713 default:
1714 NSLog(@"Case: Invalid permutation number %d", permutation);
1715 break;
1716 }
1717 NSLog(@"Completed image processing for permutation %d", i);
1718 }
1719 } else {
1720 switch (permutation) {
1721 case 1:
1722 NSLog(@"Case: Creating bitmap context with Standard RGB settings");
1723 createBitmapContextStandardRGB(cgImg, permutation);
1724 break;
1725 case 2:
1726 NSLog(@"Case: Creating bitmap context with Premultiplied First Alpha settings");
1728 break;
1729 case 3:
1730 NSLog(@"Case: Creating bitmap context with Non-Premultiplied Alpha settings");
1732 break;
1733 case 4:
1734 NSLog(@"Case: Creating bitmap context with 16-bit depth settings");
1736 break;
1737 case 5:
1738 NSLog(@"Grayscale image processing is currently pending implementation.");
1739 return;
1740 case 6:
1741 NSLog(@"Case: Creating bitmap context with HDR Float Components settings");
1743 break;
1744 case 7:
1745 NSLog(@"Case: Creating bitmap context with Alpha Only settings");
1747 break;
1748 case 8:
1749 NSLog(@"Case: Creating bitmap context with 1-bit Monochrome settings");
1751 break;
1752 case 9:
1753 NSLog(@"Case: Creating bitmap context with Big Endian pixel format settings");
1755 break;
1756 case 10:
1757 NSLog(@"Case: Creating bitmap context with Little Endian pixel format settings");
1759 break;
1760 case 11:
1761 NSLog(@"Case: Creating bitmap context with 8-bit depth, inverted colors settings");
1763 break;
1764 case 12:
1765 NSLog(@"Case: Creating bitmap context with 32-bit float, 4-component settings");
1767 break;
1768 default:
1769 NSLog(@"Case: Invalid permutation number %d", permutation);
1770 break; }
1771 NSLog(@"Completed image processing for permutation %d", permutation);
1772 }
1773}
void createBitmapContext8BitInvertedColors(CGImageRef cgImg)
Transforms the color representation of an image by inverting its colors and applying an 8-bit color d...
void createBitmapContextStandardRGB(CGImageRef cgImg, int permutation)
Creates a bitmap context with standard RGB settings, applies a fuzzing process to alter the image,...
void createBitmapContext32BitFloat4Component(CGImageRef cgImg)
Creates a bitmap context with standard RGB settings, applies a fuzzing process to alter the image,...

References createBitmapContext16BitDepth(), createBitmapContext1BitMonochrome(), createBitmapContext32BitFloat4Component(), createBitmapContext8BitInvertedColors(), createBitmapContextAlphaOnly(), createBitmapContextBigEndian(), createBitmapContextHDRFloatComponents(), createBitmapContextLittleEndian(), createBitmapContextNonPremultipliedAlpha(), createBitmapContextPremultipliedFirstAlpha(), and createBitmapContextStandardRGB().

Referenced by main(), and performAllImagePermutations().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ saveFuzzedImage()

void saveFuzzedImage ( UIImage * image,
NSString * contextDescription )

Saves a modified (fuzzed) UIImage to the documents directory.

This function takes a UIImage object that has undergone modifications (e.g., fuzzing) and saves it to the documents directory with a unique filename derived from a provided context description. It's designed to facilitate the persistence of images altered through security testing, experimental modifications, or user interactions within an application. The process includes validation of input parameters, generation of a unique filename, and the actual saving of the image in specified formats including PNG, JPEG, and GIF.

Parameters
imageThe modified UIImage object to be saved.
contextDescriptionA description of the context in which the image was modified, used to generate a unique file name.
Note
The function includes several key steps:
  • Validation: Checks contextDescription for validity to avoid file path issues.
  • Filename Generation: Creates a unique filename with "fuzzed_image_" prefix and appropriate file extension.
  • Directory Retrieval: Uses NSSearchPathForDirectoriesInDomains to find the documents directory, ensuring iOS compatibility.
  • File Path Creation: Combines the directory path with the filename.
  • Image Conversion: Encodes the UIImage as PNG, JPEG, or GIF data.
  • File Writing: Atomically writes the image data to the filesystem.
  • Logging: Outputs the result of the operation for debugging and verification.

Usage Scenarios:

  • Ideal for applications that need to save images after applying security-related fuzzing or other modifications.
  • Supports persisting images modified by user actions in editing or customization features.
  • Facilitates the creation and storage of a series of programmatically altered images for analysis or review.

Implementation Notes:

  • Assumes the UIImage and context description are valid and appropriate for the intended save operation.
  • Utilizes NSLog for logging, suitable for debugging but may require adaptation for production-level error handling or logging.

Definition at line 642 of file xnuimagefuzzer.m.

642 {
643 // Ensure contextDescription is valid to prevent file path issues
644 if (contextDescription == nil || [contextDescription length] == 0) {
645 NSLog(@"Context description is invalid.");
646 return;
647 }
648
649 // Determine the image format and file extension from contextDescription
650 NSString *fileExtension = @"png"; // Default to PNG
651 NSData *imageData;
652
653 if ([contextDescription containsString:@"jpeg"] || [contextDescription containsString:@"jpg"]) {
654 fileExtension = @"jpg";
655 imageData = UIImageJPEGRepresentation(image, 0.9); // Using a JPEG quality factor of 0.9
656 NSLog(@"Saving image as JPEG");
657 } else if ([contextDescription containsString:@"gif"]) {
658 fileExtension = @"gif";
659 imageData = UIImageGIFRepresentation(image);
660 if (imageData) {
661 NSLog(@"Successfully created GIF data");
662 } else {
663 NSLog(@"Failed to create GIF data");
664 }
665 } else if ([contextDescription containsString:@"premultipliedfirstalpha"]) {
666 // Handle PremultipliedFirstAlpha specific logic here
667 imageData = UIImagePNGRepresentation(image);
668 NSLog(@"Saving image as PNG with premultipliedfirstalpha");
669 } else {
670 // Default case handles PNG and other unspecified formats as PNG
671 imageData = UIImagePNGRepresentation(image);
672 NSLog(@"Saving image as PNG");
673 }
674
675 // Generate file name based on the context description
676 NSString *fileName = [NSString stringWithFormat:@"fuzzed_image_%@.%@", contextDescription, fileExtension];
677
678 // Fetch the documents directory path
679 NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
680 NSString *filePath = [documentsDirectory stringByAppendingPathComponent:fileName];
681
682 // Save the image data to the file
683 BOOL success = [imageData writeToFile:filePath atomically:YES];
684
685 if (success) {
686 NSLog(@"Fuzzed image for '%@' context saved to %@", contextDescription, filePath);
687 } else {
688 NSLog(@"Failed to save fuzzed image for '%@' context", contextDescription);
689 }
690}
NSData * UIImageGIFRepresentation(UIImage *image)
Creates a GIF representation of a UIImage. This custom function handles the conversion of a UIImage t...

References UIImageGIFRepresentation().

Referenced by createBitmapContext16BitDepth(), createBitmapContext32BitFloat4Component(), createBitmapContext8BitInvertedColors(), createBitmapContextAlphaOnly(), createBitmapContextBigEndian(), createBitmapContextHDRFloatComponents(), createBitmapContextLittleEndian(), createBitmapContextNonPremultipliedAlpha(), createBitmapContextPremultipliedFirstAlpha(), and createBitmapContextStandardRGB().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ saveMonochromeImage()

void saveMonochromeImage ( UIImage * image,
NSString * identifier )

Saves a monochrome UIImage with a specified identifier to the documents directory.

This function saves the provided UIImage object as a PNG file in the application's documents directory, using the specified identifier as part of the file name. It's useful for persisting processed images for later retrieval, sharing, or comparison.

Parameters
imageThe UIImage to save.
identifierA unique identifier for the image file.

Example Usage:

UIImage *monochromeImage = ...; // Assume this is a valid UIImage
NSString *identifier = @"example_monochrome_image";
saveMonochromeImage(monochromeImage, identifier);

Definition at line 791 of file xnuimagefuzzer.m.

791 {
792 NSData *imageData = UIImagePNGRepresentation(image);
793 NSString *docsDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
794 NSString *filePath = [docsDir stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.png", identifier]];
795
796 if ([imageData writeToFile:filePath atomically:YES]) {
797 NSLog(@"Saved monochrome image with identifier %@ at %@", identifier, filePath);
798 } else {
799 NSLog(@"Error saving monochrome image with identifier %@", identifier);
800 }
801}

Referenced by createBitmapContext1BitMonochrome().

+ Here is the caller graph for this function:

◆ signature()

char * signature ( void )

Definition at line 301 of file xnuimagefuzzer.m.

301 {
302 // Allocate memory using calloc; +1 for null terminator, initializing all bits to zero
303 char *signature = calloc(1, 0x10 + 1); // Replaces malloc(0x10 + 1) and initializes memory
304 if (!signature) {
305 fprintf(stderr, "Error: Failed to allocate memory for signature.\n");
306 return NULL;
307 }
308
309 // Ensure that COMM_PAGE64_BASE_ADDRESS is valid and not NULL before using memcpy
310 const char *base_address = (const char *)COMM_PAGE64_BASE_ADDRESS;
311 if (!base_address) {
312 fprintf(stderr, "Error: COMM_PAGE64_BASE_ADDRESS is null.\n");
313 free(signature);
314 return NULL;
315 }
316
317 // Copy data safely
318 memcpy(signature, base_address, 0x10);
319
320 // No need to explicitly set the null terminator since calloc initializes the memory to zero
321 return signature;
322}

References COMM_PAGE64_BASE_ADDRESS, and signature().

Referenced by dump_comm_page(), and signature().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ UIImageGIFRepresentation()

NSData * UIImageGIFRepresentation ( UIImage * image)

Creates a GIF representation of a UIImage. This custom function handles the conversion of a UIImage to GIF data using the Image I/O framework.

Parameters
imageThe UIImage to be converted.
Returns
NSData containing the GIF representation of the image.

Definition at line 701 of file xnuimagefuzzer.m.

701 {
702 // Check for valid input
703 if (!image) {
704 NSLog(@"UIImageGIFRepresentation: Invalid image input.");
705 return nil;
706 }
707
708 // Create a mutable data object to hold the GIF data
709 NSMutableData *gifData = [NSMutableData data];
710
711 // Create an image destination for the GIF data
712 CGImageDestinationRef destination = CGImageDestinationCreateWithData((CFMutableDataRef)gifData, (__bridge CFStringRef)UTTypeGIF.identifier, 1, NULL);
713
714 if (!destination) {
715 NSLog(@"UIImageGIFRepresentation: Failed to create image destination for GIF.");
716 return nil;
717 }
718
719 // Set GIF properties (e.g., loop count)
720 NSDictionary *gifProperties = @{
721 (__bridge id)kCGImagePropertyGIFDictionary: @{
722 (__bridge id)kCGImagePropertyGIFLoopCount: @0 // 0 means loop forever
723 }
724 };
725
726 // Add the image to the destination
727 CGImageDestinationAddImage(destination, image.CGImage, (__bridge CFDictionaryRef)gifProperties);
728
729 // Finalize the image destination
730 if (!CGImageDestinationFinalize(destination)) {
731 NSLog(@"UIImageGIFRepresentation: Failed to finalize the GIF image destination.");
732 CFRelease(destination);
733 return nil;
734 }
735
736 CFRelease(destination);
737 return gifData;
738}

Referenced by saveFuzzedImage().

+ Here is the caller graph for this function:

Variable Documentation

◆ cpu_cap_strings

const char* cpu_cap_strings[]
Initial value:
= {
"MMX", "SSE", "SSE2", "SSE3", "Cache32", "Cache64", "Cache128",
"FastThreadLocalStorage", "SupplementalSSE3", "64Bit", "SSE4_1", "SSE4_2",
"AES", "InOrderPipeline", "Slow", "UP", "NumCPUs", "AVX1_0", "RDRAND",
"F16C", "ENFSTRG", "FMA", "AVX2_0", "BMI1", "BMI2", "RTM", "HLE", "ADX",
"RDSEED", "MPX", "SGX"
}

Identifies the CPU's supported capabilities.

This section enumerates various CPU capabilities and instruction sets that modern processors might support. These capabilities enhance the processor's performance and security features. Identifiers for these capabilities are used to represent specific hardware features and instruction sets, such as Multimedia Extensions, Streaming SIMD Extensions, Advanced Encryption Standard instruction sets, and others.

Usage:

The identifiers provided are used to map the CPU capability bits to human-readable strings. This mapping aids developers and system administrators in understanding the features supported by the CPU on a given device, facilitating optimizations and security enhancements.

Key Identifiers:

  • MMX: Refers to Multimedia Extensions that enhance multimedia and communication tasks.
  • SSE, SSE2, SSE3, SSE4_1, SSE4_2: Streaming SIMD Extensions and their versions, improving performance on floating point and integer operations.
  • AES: Denotes support for the Advanced Encryption Standard instruction set, crucial for fast and secure data encryption.
  • AVX1_0, AVX2_0: Advanced Vector Extensions that improve performance for applications requiring high computational throughput.
  • BMI1, BMI2: Bit Manipulation Instruction Sets, enhancing the efficiency of certain data processing tasks.
  • RTM: Restricted Transactional Memory, supporting transactional memory synchronization.
  • HLE: Hardware Lock Elision, aimed at improving the performance of lock-based concurrent algorithms.
  • ADX: Multi-Precision Add-Carry Instruction Extensions, useful in cryptographic algorithms.
  • RDSEED, MPX, SGX: Various security and protection extensions, including random number generation, memory protection, and trusted execution.

Note:

The availability and support for these capabilities are highly dependent on the CPU model and the architecture of the device's processor. Detection and utilization of these features typically require querying through system-specific interfaces or leveraging instruction sets designed for this purpose.

See also
Consult the documentation for your processor or use system utilities designed to query and report CPU capabilities for detailed information on the supported features.

Definition at line 455 of file xnuimagefuzzer.m.

455 {
456 "MMX", "SSE", "SSE2", "SSE3", "Cache32", "Cache64", "Cache128",
457 "FastThreadLocalStorage", "SupplementalSSE3", "64Bit", "SSE4_1", "SSE4_2",
458 "AES", "InOrderPipeline", "Slow", "UP", "NumCPUs", "AVX1_0", "RDRAND",
459 "F16C", "ENFSTRG", "FMA", "AVX2_0", "BMI1", "BMI2", "RTM", "HLE", "ADX",
460 "RDSEED", "MPX", "SGX"
461};

Referenced by dump_comm_page().

◆ injectStrings

char* injectStrings[10]
Initial value:
= {
"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" ,
"<script>console.error('XNU Image Fuzzer');</script>" ,
"' OR ''='" ,
"%d %s %d %s" ,
"XNU Image Fuzzer" ,
"123456; DROP TABLE users" ,
"!@#$%^&*()_+=" ,
"..//..//..//win" ,
"\0\0\0" ,
"<?xml version=\"1.0\"?><!DOCTYPE replace [<!ENTITY example \"XNUImageFuzzer\"> ]><userInfo><firstName>XNUImageFuzzer<&example;></firstName></userInfo>"
}

Definition at line 190 of file xnuimagefuzzer.m.

190 {
201};
#define INJECT_STRING_9
#define INJECT_STRING_7
#define INJECT_STRING_1
Configures robust strings for security testing within the application.
#define INJECT_STRING_2
#define INJECT_STRING_4
#define INJECT_STRING_6
#define INJECT_STRING_10
#define INJECT_STRING_3
#define INJECT_STRING_5
#define INJECT_STRING_8

Referenced by applyEnhancedFuzzingToBitmapContext(), applyEnhancedFuzzingToBitmapContextWithFloats(), and applyFuzzingToBitmapContext().

◆ verboseLogging

int verboseLogging = 0
static

Core and external libraries necessary for the fuzzer functionality.

This section includes the necessary headers for the Foundation framework, UIKit, Core Graphics, standard input/output, standard library, memory management, mathematical functions, Boolean type, floating-point limits, and string functions. These libraries support image processing, UI interaction, and basic C operations essential for the application.

Definition at line 62 of file xnuimagefuzzer.m.

Referenced by applyEnhancedFuzzingToBitmapContext(), applyEnhancedFuzzingToBitmapContextAlphaOnly(), applyEnhancedFuzzingToBitmapContextWithFloats(), createBitmapContextStandardRGB(), and logPixelData().