first and last commit

This commit is contained in:
Chris Nutter committed 2023-07-08 13:03:17 -07:00
commit 1bf4efd552
2612 files changed
+636500

No files matched your search

+154
View File
@@ -0,0 +1,154 @@
/*
* Copyright (C) 2013 Apple Inc. All rights reserved.
* Copyright (C) 2007-2011 Apple Inc. All rights reserved.
* Copyright (c) 2000-2006 Apple Computer, Inc. All rights reserved.
*
* @APPLE_LICENSE_HEADER_START@
*
* The contents of this file constitute Original Code as defined in and
* are subject to the Apple Public Source License Version 1.1 (the
* "License"). You may not use this file except in compliance with the
* License. Please obtain a copy of the License at
* http://www.apple.com/publicsource and read it before using this file.
*
* This Original Code and all software distributed under the License are
* distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, EITHER
* EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
* INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT. Please see the
* License for the specific language governing rights and limitations
* under the License.
*
* @APPLE_LICENSE_HEADER_END@
*/
/*
* cache.c - A simple cache for file systems meta-data.
*
* Copyright (c) 2000 - 2003 Apple Computer, Inc.
*
* DRI: Josh de Cesare
*/
#include <sys/types.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include "hfs.h"
struct CacheEntry {
CICell ih;
time_t time;
off_t offset;
};
typedef struct CacheEntry CacheEntry;
#define kCacheSize (kFSCacheSize)
#define kCacheMinBlockSize (0x200)
#define kCacheMaxBlockSize (0x4000)
#define kCacheMaxEntries (kCacheSize / kCacheMinBlockSize)
static CICell gCacheIH;
static uint32_t gCacheBlockSize;
static uint32_t gCacheNumEntries;
static time_t gCacheTime;
static CacheEntry gCacheEntries[kCacheMaxEntries];
static uint8_t *gCacheBuffer;
uint32_t gCacheHits;
uint32_t gCacheMisses;
uint32_t gCacheEvicts;
void CacheInit(CICell ih, uint32_t blockSize)
{
if ((blockSize < kCacheMinBlockSize) ||
(blockSize >= kCacheMaxBlockSize))
return;
if (gCacheBuffer)
free(gCacheBuffer);
posix_memalign((void **)&gCacheBuffer, blockSize, kFSCacheSize);
gCacheBlockSize = blockSize;
gCacheNumEntries = kCacheSize / gCacheBlockSize;
gCacheTime = 0;
gCacheHits = 0;
gCacheMisses = 0;
gCacheEvicts = 0;
bzero(gCacheEntries, sizeof(gCacheEntries));
gCacheIH = ih;
}
uint32_t CacheRead(CICell ih, uint8_t *buffer, off_t offset,
uint32_t length, bool cache)
{
uint32_t cnt, oldestEntry = 0, loadCache = 0;
uint32_t result;
CacheEntry *entry;
time_t oldestTime;
// See if the data can be cached.
if (cache && (gCacheIH == ih) && (length == gCacheBlockSize)) {
// Look for the data in the cache.
for (cnt = 0; cnt < gCacheNumEntries; cnt++) {
entry = &gCacheEntries[cnt];
if ((entry->ih == ih) && (entry->offset == offset)) {
entry->time = ++gCacheTime;
break;
}
}
// If the data was found copy it to the caller.
if (cnt != gCacheNumEntries) {
memcpy(buffer, gCacheBuffer + cnt * gCacheBlockSize, gCacheBlockSize);
gCacheHits++;
return gCacheBlockSize;
}
// Could not find the data in the cache.
loadCache = 1;
}
// Read the data from the disk.
// <rdar://problem/12080714> CacheRead (in HFS) should return actual amount read
result = (uint32_t) HFSBlockRead(ih, (CICell)buffer, offset, length);
if (cache) gCacheMisses++;
// Put the data from the disk in the cache if needed and if read completed
// successfully
if (loadCache && (result == length)) {
// Find a free entry.
oldestTime = gCacheTime;
for (cnt = 0; cnt < gCacheNumEntries; cnt++) {
entry = &gCacheEntries[cnt];
// Found a free entry.
if (entry->ih == 0) break;
if (entry->time < oldestTime) {
oldestTime = entry->time;
oldestEntry = cnt;
}
}
// If no free entry was found, use the oldest.
if (cnt == gCacheNumEntries) {
cnt = oldestEntry;
gCacheEvicts++;
}
// Copy the data from disk to the new entry.
entry = &gCacheEntries[cnt];
entry->ih = ih;
entry->time = ++gCacheTime;
entry->offset = offset;
memcpy(gCacheBuffer + cnt * gCacheBlockSize, buffer, gCacheBlockSize);
}
return result;
}
+89
View File
@@ -0,0 +1,89 @@
#include <stdint.h>
#include <unittest.h>
#include <lib/blockdev.h>
#include <lib/fs.h>
#include <stdlib.h>
#include <string.h>
struct blockdev *create_mock_blockdev(const char *name, const char *filename, uint32_t block_size);
void walk(const char *dirpath)
{
int dirfd;
struct dirent ent;
int result;
dirfd = fs_opendir(dirpath);
if (dirfd < 0) {
printf("error opening dir '%s'\n", dirpath);
return;
}
while ((result = fs_readdir(dirfd, &ent)) >= 0) {
size_t subpath_size = strlen(dirpath) + 1 + strlen(ent.d_name) + 1;
char *subpath = malloc(subpath_size);
snprintf(subpath, subpath_size, "%s/%s", dirpath, ent.d_name);
if (ent.d_type == FILE_TYPE_FILE) {
int fd;
printf("%s\n", subpath);
fd = fs_open(subpath, 0);
if (fd >= 0) {
void *buffer;
struct stat st;
if (fs_stat(fd, &st) >= 0) {
unsigned size = st.st_size;
if (size > 1000000)
size = 1000000;
buffer = malloc(size);
if (fs_read(fd, buffer, size) < 0) {
printf("error reading file '%s'\n", subpath);
}
free(buffer);
} else {
printf("error statting file '%s'\n", subpath);
}
} else {
printf("error opening file '%s'\n", subpath);
}
} else if (ent.d_type == FILE_TYPE_DIR) {
printf("%s/\n", subpath);
walk(subpath);
}
free(subpath);
}
fs_closedir(dirfd);
}
int fuzz_main(const char *filename)
{
struct blockdev *bdev;
int result;
bdev = create_mock_blockdev("dev", filename, 4096);
register_blockdev(bdev);
result = fs_mount("dev", "hfs", "/boot");
if (result == 0) {
printf("Mount succeeded\n");
walk("/boot");
}
return 0;
}
// Mock
bool
env_blacklist(const char *name, bool write)
{
return false;
}
// Mock
bool
env_blacklist_nvram(const char *name)
{
return false;
}
+1372
View File
File diff suppressed because it is too large. Load diff
+134
View File
@@ -0,0 +1,134 @@
/*
* Copyright (c) 2000 Apple Computer, Inc. All rights reserved.
*
* @APPLE_LICENSE_HEADER_START@
*
* The contents of this file constitute Original Code as defined in and
* are subject to the Apple Public Source License Version 1.1 (the
* "License"). You may not use this file except in compliance with the
* License. Please obtain a copy of the License at
* http://www.apple.com/publicsource and read it before using this file.
*
* This Original Code and all software distributed under the License are
* distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, EITHER
* EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
* INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT. Please see the
* License for the specific language governing rights and limitations
* under the License.
*
* @APPLE_LICENSE_HEADER_END@
*/
/* Derived from: */
/*
* fs.h - Externs for the File System Modules
*
* Copyright (c) 1999-2004 Apple Computer, Inc.
*
* DRI: Josh de Cesare
*/
#ifndef _BOOTX_FS_H_
#define _BOOTX_FS_H_
// tunable
#define kFSCacheSize (64 * 1024)
// File Permissions and Types
enum {
kPermOtherExecute = 1 << 0,
kPermOtherWrite = 1 << 1,
kPermOtherRead = 1 << 2,
kPermGroupExecute = 1 << 3,
kPermGroupWrite = 1 << 4,
kPermGroupRead = 1 << 5,
kPermOwnerExecute = 1 << 6,
kPermOwnerWrite = 1 << 7,
kPermOwnerRead = 1 << 8,
kPermMask = 0x1FF,
kOwnerNotRoot = 1 << 9,
kFileTypeUnknown = 0x0 << 16,
kFileTypeFlat = 0x1 << 16,
kFileTypeDirectory = 0x2 << 16,
kFileTypeLink = 0x3 << 16,
kFileTypeMask = 0x3 << 16
};
typedef void *CICell;
// Externs for cache.c
extern uint32_t gCacheHits;
extern uint32_t gCacheMisses;
extern uint32_t gCacheEvicts;
extern void CacheInit(CICell ih, uint32_t chunkSize);
extern uint32_t CacheRead(CICell ih, uint8_t *buffer, off_t offset,
uint32_t length, bool cache);
// Externs for hfs.c
extern int HFSInitPartition(CICell ih);
extern int HFSDetect(void);
extern int HFSReadFile(CICell ih, const char *filePath, void *base, off_t offset, size_t length);
extern int HFSGetFileInfo(CICell ih, const char *filePath, uint32_t *flags, time_t *time, off_t *size);
extern int HFSGetDirEntry(CICell ih, const char *dirPath, off_t *dirIndex, char *name, size_t nameSize, uint32_t *flags, time_t *time, off_t *size);
extern struct HFSPlusVolumeHeader *HFSGetVolumeHeader(void);
// Externs for hfs_fs.c
extern int HFSBlockRead(CICell *ih, void *buf, off_t offset, uint32_t length);
/*
* We may need to work with big-endian data that's not
* aligned. For ARM at least, this is an issue. Rather
* than use swap functions and macrotize, these are explicitly
* called out to avoid alignment issues even on big-endian systems.
*
* No these aren't efficient. No, it doesn't really matter...
*/
static inline u_int64_t
HFSntohll(const void *ov)
{
unsigned const char *ovb = (unsigned const char *)ov;
return(((u_int64_t)ovb[0] << 56) +
((u_int64_t)ovb[1] << 48) +
((u_int64_t)ovb[2] << 40) +
((u_int64_t)ovb[3] << 32) +
((u_int64_t)ovb[4] << 24) +
((u_int64_t)ovb[5] << 16) +
((u_int64_t)ovb[6] << 8) +
(u_int64_t)ovb[7]);
}
static inline u_int32_t
HFSntohl(const void *ov)
{
unsigned const char *ovb = (unsigned const char *)ov;
return(((u_int32_t)ovb[0] << 24) +
((u_int32_t)ovb[1] << 16) +
((u_int32_t)ovb[2] << 8) +
(u_int32_t)ovb[3]);
}
static inline u_int16_t
HFSntohs(const void *ov)
{
unsigned const char *ovb = (unsigned const char *)ov;
return(((u_int16_t)ovb[0] << 8) + (u_int16_t)ovb[1]);
}
static inline short
HFShtons(const unsigned short ov)
{
unsigned short nv;
unsigned char *nvb = (unsigned char *)&nv;
nvb[0] = (ov >> 8);
nvb[1] = ov & 0xff;
return(nv);
}
#endif /* ! _BOOTX_FS_H_ */
+746
View File
@@ -0,0 +1,746 @@
/*
* Copyright (C) 2007-2011 Apple Inc. All rights reserved.
* Copyright (c) 2000-2006 Apple Computer, Inc. All rights reserved.
*
* @APPLE_LICENSE_HEADER_START@
*
* This file contains Original Code and/or Modifications of Original Code
* as defined in and that are subject to the Apple Public Source License
* Version 2.0 (the 'License'). You may not use this file except in
* compliance with the License. Please obtain a copy of the License at
* http://www.opensource.apple.com/apsl/ and read it before using this
* file.
*
* The Original Code and all software distributed under the License are
* distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
* EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
* INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
* Please see the License for the specific language governing rights and
* limitations under the License.
*
* @APPLE_LICENSE_HEADER_END@
*/
#ifndef __HFS_FORMAT__
#define __HFS_FORMAT__
/*
* hfs_format.c
*
* This file describes the on-disk format for HFS and HFS Plus volumes.
* The HFS Plus volume format is desciibed in detail in Apple Technote 1150.
*
* http://developer.apple.com/technotes/tn/tn1150.html
*
*/
#ifdef __cplusplus
extern "C" {
#endif
/* some on-disk hfs structures have 68K alignment (misaligned) */
/* Signatures used to differentiate between HFS and HFS Plus volumes */
enum {
kHFSSigWord = 0x4244, /* 'BD' in ASCII */
kHFSPlusSigWord = 0x482B, /* 'H+' in ASCII */
kHFSXSigWord = 0x4858, /* 'HX' in ASCII */
kHFSPlusVersion = 0x0004, /* 'H+' volumes are version 4 only */
kHFSXVersion = 0x0005, /* 'HX' volumes start with version 5 */
kHFSPlusMountVersion = 0x31302E30, /* '10.0' for Mac OS X */
kHFSJMountVersion = 0x4846534a, /* 'HFSJ' for journaled HFS+ on OS X */
kFSKMountVersion = 0x46534b21 /* 'FSK!' for failed journal replay */
};
#ifdef __APPLE_API_PRIVATE
/*
* Mac OS X has two special directories on HFS+ volumes for hardlinked files
* and hardlinked directories as well as for open-unlinked files.
*
* These directories and their contents are not exported from the filesystem
* under Mac OS X.
*/
#define HFSPLUSMETADATAFOLDER "\xE2\x90\x80\xE2\x90\x80\xE2\x90\x80\xE2\x90\x80HFS+ Private Data"
#define HFSPLUS_ARCHIVED_FOLDERS ".Archived_Directories\x0d"
/*
* Files in the "HFS+ Private Data" folder have one of the following prefixes
* followed by a decimal number (no leading zeros) for the file ID.
*
* Note: Earlier version of Mac OS X used a 32 bit random number for the link
* ref number instead of the file id.
*
* e.g. iNode7182000 and temp3296
*/
#define HFS_INODE_PREFIX "iNode"
#define HFS_DELETE_PREFIX "temp"
/*
* Files in the ".Archived_Directories" folder have the following prefix
* followed by a decimal number (no leading zeros) for the file ID.
*
* e.g. dir_555
*/
#define HFS_DIRINODE_PREFIX "dir_"
/*
* Hardlink inodes save the head of the link chain in
* an extended attribute named FIRST_LINK_XATTR_NAME.
* The attribute data is the decimal value in ASCII
* of the cnid for the first link in the chain.
*
* This extended attribute is private (i.e. its not
* exported in the getxattr/listxattr POSIX APIs).
*/
#define FIRST_LINK_XATTR_NAME "com.apple.system.hfs.firstlink"
#define FIRST_LINK_XATTR_REC_SIZE (sizeof(HFSPlusAttrData) - 2 + 12)
#endif /* __APPLE_API_PRIVATE */
/*
* Indirect link files (hard links) have the following type/creator.
*/
enum {
kHardLinkFileType = 0x686C6E6B, /* 'hlnk' */
kHFSPlusCreator = 0x6866732B /* 'hfs+' */
};
/*
* File type and creator for symbolic links
*/
enum {
kSymLinkFileType = 0x736C6E6B, /* 'slnk' */
kSymLinkCreator = 0x72686170 /* 'rhap' */
};
#ifndef _HFSUNISTR255_DEFINED_
#define _HFSUNISTR255_DEFINED_
/* Unicode strings are used for HFS Plus file and folder names */
struct HFSUniStr255 {
uint16_t length; /* number of unicode characters */
uint16_t unicode[255]; /* unicode characters */
} __attribute__((aligned(2), packed));
typedef struct HFSUniStr255 HFSUniStr255;
typedef const HFSUniStr255 *ConstHFSUniStr255Param;
#endif /* _HFSUNISTR255_DEFINED_ */
enum {
kHFSMaxVolumeNameChars = 27,
kHFSMaxFileNameChars = 31,
kHFSPlusMaxFileNameChars = 255
};
/* Extent overflow file data structures */
/* HFS Extent key */
struct HFSExtentKey {
uint8_t keyLength; /* length of key, excluding this field */
uint8_t forkType; /* 0 = data fork, FF = resource fork */
uint32_t fileID; /* file ID */
uint16_t startBlock; /* first file allocation block number in this extent */
} __attribute__((aligned(2), packed));
typedef struct HFSExtentKey HFSExtentKey;
/* HFS Plus Extent key */
struct HFSPlusExtentKey {
uint16_t keyLength; /* length of key, excluding this field */
uint8_t forkType; /* 0 = data fork, FF = resource fork */
uint8_t pad; /* make the other fields align on 32-bit boundary */
uint32_t fileID; /* file ID */
uint32_t startBlock; /* first file allocation block number in this extent */
} __attribute__((aligned(2), packed));
typedef struct HFSPlusExtentKey HFSPlusExtentKey;
/* Number of extent descriptors per extent record */
enum {
kHFSExtentDensity = 3,
kHFSPlusExtentDensity = 8
};
/* HFS extent descriptor */
struct HFSExtentDescriptor {
uint16_t startBlock; /* first allocation block */
uint16_t blockCount; /* number of allocation blocks */
} __attribute__((aligned(2), packed));
typedef struct HFSExtentDescriptor HFSExtentDescriptor;
/* HFS Plus extent descriptor */
struct HFSPlusExtentDescriptor {
uint32_t startBlock; /* first allocation block */
uint32_t blockCount; /* number of allocation blocks */
} __attribute__((aligned(2), packed));
typedef struct HFSPlusExtentDescriptor HFSPlusExtentDescriptor;
/* HFS extent record */
typedef HFSExtentDescriptor HFSExtentRecord[3];
/* HFS Plus extent record */
typedef HFSPlusExtentDescriptor HFSPlusExtentRecord[8];
/* Finder information */
struct FndrFileInfo {
uint32_t fdType; /* file type */
uint32_t fdCreator; /* file creator */
uint16_t fdFlags; /* Finder flags */
struct {
int16_t v; /* file's location */
int16_t h;
} fdLocation;
int16_t opaque;
} __attribute__((aligned(2), packed));
typedef struct FndrFileInfo FndrFileInfo;
struct FndrDirInfo {
struct { /* folder's window rectangle */
int16_t top;
int16_t left;
int16_t bottom;
int16_t right;
} frRect;
unsigned short frFlags; /* Finder flags */
struct {
uint16_t v; /* folder's location */
uint16_t h;
} frLocation;
int16_t opaque;
} __attribute__((aligned(2), packed));
typedef struct FndrDirInfo FndrDirInfo;
struct FndrOpaqueInfo {
int8_t opaque[16];
} __attribute__((aligned(2), packed));
typedef struct FndrOpaqueInfo FndrOpaqueInfo;
/* HFS Plus Fork data info - 80 bytes */
struct HFSPlusForkData {
uint64_t logicalSize; /* fork's logical size in bytes */
uint32_t clumpSize; /* fork's clump size in bytes */
uint32_t totalBlocks; /* total blocks used by this fork */
HFSPlusExtentRecord extents; /* initial set of extents */
} __attribute__((aligned(2), packed));
typedef struct HFSPlusForkData HFSPlusForkData;
/* Mac OS X has 16 bytes worth of "BSD" info.
*
* Note: Mac OS 9 implementations and applications
* should preserve, but not change, this information.
*/
struct HFSPlusBSDInfo {
uint32_t ownerID; /* user-id of owner or hard link chain previous link */
uint32_t groupID; /* group-id of owner or hard link chain next link */
uint8_t adminFlags; /* super-user changeable flags */
uint8_t ownerFlags; /* owner changeable flags */
uint16_t fileMode; /* file type and permission bits */
union {
uint32_t iNodeNum; /* indirect node number (hard links only) */
uint32_t linkCount; /* links that refer to this indirect node */
uint32_t rawDevice; /* special file device (FBLK and FCHR only) */
} special;
} __attribute__((aligned(2), packed));
typedef struct HFSPlusBSDInfo HFSPlusBSDInfo;
/*
* Hardlink "links" resolve to an inode
* and the actual uid/gid comes from that
* inode.
*
* We repurpose the links's uid/gid fields
* for the hardlink link chain. The chain
* consists of a doubly linked list of file
* ids.
*/
#define hl_firstLinkID reserved1 /* Valid only if HasLinkChain flag is set (indirect nodes only) */
#define hl_prevLinkID bsdInfo.ownerID /* Valid only if HasLinkChain flag is set */
#define hl_nextLinkID bsdInfo.groupID /* Valid only if HasLinkChain flag is set */
#define hl_linkReference bsdInfo.special.iNodeNum
#define hl_linkCount bsdInfo.special.linkCount
/* Catalog file data structures */
enum {
kHFSRootParentID = 1, /* Parent ID of the root folder */
kHFSRootFolderID = 2, /* Folder ID of the root folder */
kHFSExtentsFileID = 3, /* File ID of the extents file */
kHFSCatalogFileID = 4, /* File ID of the catalog file */
kHFSBadBlockFileID = 5, /* File ID of the bad allocation block file */
kHFSAllocationFileID = 6, /* File ID of the allocation file (HFS Plus only) */
kHFSStartupFileID = 7, /* File ID of the startup file (HFS Plus only) */
kHFSAttributesFileID = 8, /* File ID of the attribute file (HFS Plus only) */
kHFSAttributeDataFileID = 13, /* Used in Mac OS X runtime for extent based attributes */
/* kHFSAttributeDataFileID is never stored on disk. */
kHFSRepairCatalogFileID = 14, /* Used when rebuilding Catalog B-tree */
kHFSBogusExtentFileID = 15, /* Used for exchanging extents in extents file */
kHFSFirstUserCatalogNodeID = 16
};
/* HFS catalog key */
struct HFSCatalogKey {
uint8_t keyLength; /* key length (in bytes) */
uint8_t reserved; /* reserved (set to zero) */
uint32_t parentID; /* parent folder ID */
uint8_t nodeName[kHFSMaxFileNameChars + 1]; /* catalog node name */
} __attribute__((aligned(2), packed));
typedef struct HFSCatalogKey HFSCatalogKey;
/* HFS Plus catalog key */
struct HFSPlusCatalogKey {
uint16_t keyLength; /* key length (in bytes) */
uint32_t parentID; /* parent folder ID */
HFSUniStr255 nodeName; /* catalog node name */
} __attribute__((aligned(2), packed));
typedef struct HFSPlusCatalogKey HFSPlusCatalogKey;
/* Catalog record types */
enum {
/* HFS Catalog Records */
kHFSFolderRecord = 0x0100, /* Folder record */
kHFSFileRecord = 0x0200, /* File record */
kHFSFolderThreadRecord = 0x0300, /* Folder thread record */
kHFSFileThreadRecord = 0x0400, /* File thread record */
/* HFS Plus Catalog Records */
kHFSPlusFolderRecord = 1, /* Folder record */
kHFSPlusFileRecord = 2, /* File record */
kHFSPlusFolderThreadRecord = 3, /* Folder thread record */
kHFSPlusFileThreadRecord = 4 /* File thread record */
};
/* Catalog file record flags */
enum {
kHFSFileLockedBit = 0x0000, /* file is locked and cannot be written to */
kHFSFileLockedMask = 0x0001,
kHFSThreadExistsBit = 0x0001, /* a file thread record exists for this file */
kHFSThreadExistsMask = 0x0002,
kHFSHasAttributesBit = 0x0002, /* object has extended attributes */
kHFSHasAttributesMask = 0x0004,
kHFSHasSecurityBit = 0x0003, /* object has security data (ACLs) */
kHFSHasSecurityMask = 0x0008,
kHFSHasFolderCountBit = 0x0004, /* folder maintains a seperate sub-folder count */
kHFSHasFolderCountMask = 0x0010,
kHFSHasLinkChainBit = 0x0005, /* has hardlink chain (inode or link) */
kHFSHasLinkChainMask = 0x0020,
kHFSHasChildLinkBit = 0x0006, /* folder has a child that's a dir link */
kHFSHasChildLinkMask = 0x0040
};
/* HFS catalog folder record - 70 bytes */
struct HFSCatalogFolder {
int16_t recordType; /* == kHFSFolderRecord */
uint16_t flags; /* folder flags */
uint16_t valence; /* folder valence */
uint32_t folderID; /* folder ID */
uint32_t createDate; /* date and time of creation */
uint32_t modifyDate; /* date and time of last modification */
uint32_t backupDate; /* date and time of last backup */
FndrDirInfo userInfo; /* Finder information */
FndrOpaqueInfo finderInfo; /* additional Finder information */
uint32_t reserved[4]; /* reserved - initialized as zero */
} __attribute__((aligned(2), packed));
typedef struct HFSCatalogFolder HFSCatalogFolder;
/* HFS Plus catalog folder record - 88 bytes */
struct HFSPlusCatalogFolder {
int16_t recordType; /* == kHFSPlusFolderRecord */
uint16_t flags; /* file flags */
uint32_t valence; /* folder's item count */
uint32_t folderID; /* folder ID */
uint32_t createDate; /* date and time of creation */
uint32_t contentModDate; /* date and time of last content modification */
uint32_t attributeModDate; /* date and time of last attribute modification */
uint32_t accessDate; /* date and time of last access (MacOS X only) */
uint32_t backupDate; /* date and time of last backup */
HFSPlusBSDInfo bsdInfo; /* permissions (for MacOS X) */
FndrDirInfo userInfo; /* Finder information */
FndrOpaqueInfo finderInfo; /* additional Finder information */
uint32_t textEncoding; /* hint for name conversions */
uint32_t folderCount; /* number of enclosed folders, active when HasFolderCount is set */
} __attribute__((aligned(2), packed));
typedef struct HFSPlusCatalogFolder HFSPlusCatalogFolder;
/* HFS catalog file record - 102 bytes */
struct HFSCatalogFile {
int16_t recordType; /* == kHFSFileRecord */
uint8_t flags; /* file flags */
int8_t fileType; /* file type (unused ?) */
FndrFileInfo userInfo; /* Finder information */
uint32_t fileID; /* file ID */
uint16_t dataStartBlock; /* not used - set to zero */
int32_t dataLogicalSize; /* logical EOF of data fork */
int32_t dataPhysicalSize; /* physical EOF of data fork */
uint16_t rsrcStartBlock; /* not used - set to zero */
int32_t rsrcLogicalSize; /* logical EOF of resource fork */
int32_t rsrcPhysicalSize; /* physical EOF of resource fork */
uint32_t createDate; /* date and time of creation */
uint32_t modifyDate; /* date and time of last modification */
uint32_t backupDate; /* date and time of last backup */
FndrOpaqueInfo finderInfo; /* additional Finder information */
uint16_t clumpSize; /* file clump size (not used) */
HFSExtentRecord dataExtents; /* first data fork extent record */
HFSExtentRecord rsrcExtents; /* first resource fork extent record */
uint32_t reserved; /* reserved - initialized as zero */
} __attribute__((aligned(2), packed));
typedef struct HFSCatalogFile HFSCatalogFile;
/* HFS Plus catalog file record - 248 bytes */
struct HFSPlusCatalogFile {
int16_t recordType; /* == kHFSPlusFileRecord */
uint16_t flags; /* file flags */
uint32_t reserved1; /* reserved - initialized as zero */
uint32_t fileID; /* file ID */
uint32_t createDate; /* date and time of creation */
uint32_t contentModDate; /* date and time of last content modification */
uint32_t attributeModDate; /* date and time of last attribute modification */
uint32_t accessDate; /* date and time of last access (MacOS X only) */
uint32_t backupDate; /* date and time of last backup */
HFSPlusBSDInfo bsdInfo; /* permissions (for MacOS X) */
FndrFileInfo userInfo; /* Finder information */
FndrOpaqueInfo finderInfo; /* additional Finder information */
uint32_t textEncoding; /* hint for name conversions */
uint32_t reserved2; /* reserved - initialized as zero */
/* Note: these start on double long (64 bit) boundry */
HFSPlusForkData dataFork; /* size and block data for data fork */
HFSPlusForkData resourceFork; /* size and block data for resource fork */
} __attribute__((aligned(2), packed));
typedef struct HFSPlusCatalogFile HFSPlusCatalogFile;
/* HFS catalog thread record - 46 bytes */
struct HFSCatalogThread {
int16_t recordType; /* == kHFSFolderThreadRecord or kHFSFileThreadRecord */
int32_t reserved[2]; /* reserved - initialized as zero */
uint32_t parentID; /* parent ID for this catalog node */
uint8_t nodeName[kHFSMaxFileNameChars + 1]; /* name of this catalog node */
} __attribute__((aligned(2), packed));
typedef struct HFSCatalogThread HFSCatalogThread;
/* HFS Plus catalog thread record -- 264 bytes */
struct HFSPlusCatalogThread {
int16_t recordType; /* == kHFSPlusFolderThreadRecord or kHFSPlusFileThreadRecord */
int16_t reserved; /* reserved - initialized as zero */
uint32_t parentID; /* parent ID for this catalog node */
HFSUniStr255 nodeName; /* name of this catalog node (variable length) */
} __attribute__((aligned(2), packed));
typedef struct HFSPlusCatalogThread HFSPlusCatalogThread;
#ifdef __APPLE_API_UNSTABLE
/*
These are the types of records in the attribute B-tree. The values were
chosen so that they wouldn't conflict with the catalog record types.
*/
enum {
kHFSPlusAttrInlineData = 0x10, /* attributes whose data fits in a b-tree node */
kHFSPlusAttrForkData = 0x20, /* extent based attributes (data lives in extents) */
kHFSPlusAttrExtents = 0x30 /* overflow extents for large attributes */
};
/*
HFSPlusAttrForkData
For larger attributes, whose value is stored in allocation blocks.
If the attribute has more than 8 extents, there will be additonal
records (of type HFSPlusAttrExtents) for this attribute.
*/
struct HFSPlusAttrForkData {
uint32_t recordType; /* == kHFSPlusAttrForkData*/
uint32_t reserved;
HFSPlusForkData theFork; /* size and first extents of value*/
} __attribute__((aligned(2), packed));
typedef struct HFSPlusAttrForkData HFSPlusAttrForkData;
/*
HFSPlusAttrExtents
This record contains information about overflow extents for large,
fragmented attributes.
*/
struct HFSPlusAttrExtents {
uint32_t recordType; /* == kHFSPlusAttrExtents*/
uint32_t reserved;
HFSPlusExtentRecord extents; /* additional extents*/
} __attribute__((aligned(2), packed));
typedef struct HFSPlusAttrExtents HFSPlusAttrExtents;
/*
* Atrributes B-tree Data Record
*
* For small attributes, whose entire value is stored
* within a single B-tree record.
*/
struct HFSPlusAttrData {
uint32_t recordType; /* == kHFSPlusAttrInlineData */
uint32_t reserved[2];
uint32_t attrSize; /* size of attribute data in bytes */
uint8_t attrData[2]; /* variable length */
} __attribute__((aligned(2), packed));
typedef struct HFSPlusAttrData HFSPlusAttrData;
/* HFSPlusAttrInlineData is obsolete use HFSPlusAttrData instead */
struct HFSPlusAttrInlineData {
uint32_t recordType;
uint32_t reserved;
uint32_t logicalSize;
uint8_t userData[2];
} __attribute__((aligned(2), packed));
typedef struct HFSPlusAttrInlineData HFSPlusAttrInlineData;
/* A generic Attribute Record*/
union HFSPlusAttrRecord {
uint32_t recordType;
HFSPlusAttrInlineData inlineData; /* NOT USED */
HFSPlusAttrData attrData;
HFSPlusAttrForkData forkData;
HFSPlusAttrExtents overflowExtents;
};
typedef union HFSPlusAttrRecord HFSPlusAttrRecord;
/* Attribute key */
enum { kHFSMaxAttrNameLen = 127 };
struct HFSPlusAttrKey {
uint16_t keyLength; /* key length (in bytes) */
uint16_t pad; /* set to zero */
uint32_t fileID; /* file associated with attribute */
uint32_t startBlock; /* first allocation block number for extents */
uint16_t attrNameLen; /* number of unicode characters */
uint16_t attrName[kHFSMaxAttrNameLen]; /* attribute name (Unicode) */
} __attribute__((aligned(2), packed));
typedef struct HFSPlusAttrKey HFSPlusAttrKey;
#define kHFSPlusAttrKeyMaximumLength (sizeof(HFSPlusAttrKey) - sizeof(uint16_t))
#define kHFSPlusAttrKeyMinimumLength (kHFSPlusAttrKeyMaximumLength - kHFSMaxAttrNameLen*sizeof(uint16_t))
#endif /* __APPLE_API_UNSTABLE */
/* Key and node lengths */
enum {
kHFSPlusExtentKeyMaximumLength = sizeof(HFSPlusExtentKey) - sizeof(uint16_t),
kHFSExtentKeyMaximumLength = sizeof(HFSExtentKey) - sizeof(uint8_t),
kHFSPlusCatalogKeyMaximumLength = sizeof(HFSPlusCatalogKey) - sizeof(uint16_t),
kHFSPlusCatalogKeyMinimumLength = kHFSPlusCatalogKeyMaximumLength - sizeof(HFSUniStr255) + sizeof(uint16_t),
kHFSCatalogKeyMaximumLength = sizeof(HFSCatalogKey) - sizeof(uint8_t),
kHFSCatalogKeyMinimumLength = kHFSCatalogKeyMaximumLength - (kHFSMaxFileNameChars + 1) + sizeof(uint8_t),
kHFSPlusCatalogMinNodeSize = 4096,
kHFSPlusExtentMinNodeSize = 512,
kHFSPlusAttrMinNodeSize = 4096
};
/* HFS and HFS Plus volume attribute bits */
enum {
/* Bits 0-6 are reserved (always cleared by MountVol call) */
kHFSVolumeHardwareLockBit = 7, /* volume is locked by hardware */
kHFSVolumeUnmountedBit = 8, /* volume was successfully unmounted */
kHFSVolumeSparedBlocksBit = 9, /* volume has bad blocks spared */
kHFSVolumeNoCacheRequiredBit = 10, /* don't cache volume blocks (i.e. RAM or ROM disk) */
kHFSBootVolumeInconsistentBit = 11, /* boot volume is inconsistent (System 7.6 and later) */
kHFSCatalogNodeIDsReusedBit = 12,
kHFSVolumeJournaledBit = 13, /* this volume has a journal on it */
kHFSVolumeInconsistentBit = 14, /* serious inconsistencies detected at runtime */
kHFSVolumeSoftwareLockBit = 15, /* volume is locked by software */
kHFSVolumeHardwareLockMask = 1 << kHFSVolumeHardwareLockBit,
kHFSVolumeUnmountedMask = 1 << kHFSVolumeUnmountedBit,
kHFSVolumeSparedBlocksMask = 1 << kHFSVolumeSparedBlocksBit,
kHFSVolumeNoCacheRequiredMask = 1 << kHFSVolumeNoCacheRequiredBit,
kHFSBootVolumeInconsistentMask = 1 << kHFSBootVolumeInconsistentBit,
kHFSCatalogNodeIDsReusedMask = 1 << kHFSCatalogNodeIDsReusedBit,
kHFSVolumeJournaledMask = 1 << kHFSVolumeJournaledBit,
kHFSVolumeInconsistentMask = 1 << kHFSVolumeInconsistentBit,
kHFSVolumeSoftwareLockMask = 1 << kHFSVolumeSoftwareLockBit,
kHFSMDBAttributesMask = 0x8380
};
/* HFS Master Directory Block - 162 bytes */
/* Stored at sector #2 (3rd sector) and second-to-last sector. */
struct HFSMasterDirectoryBlock {
uint16_t drSigWord; /* == kHFSSigWord */
uint32_t drCrDate; /* date and time of volume creation */
uint32_t drLsMod; /* date and time of last modification */
uint16_t drAtrb; /* volume attributes */
uint16_t drNmFls; /* number of files in root folder */
uint16_t drVBMSt; /* first block of volume bitmap */
uint16_t drAllocPtr; /* start of next allocation search */
uint16_t drNmAlBlks; /* number of allocation blocks in volume */
uint32_t drAlBlkSiz; /* size (in bytes) of allocation blocks */
uint32_t drClpSiz; /* default clump size */
uint16_t drAlBlSt; /* first allocation block in volume */
uint32_t drNxtCNID; /* next unused catalog node ID */
uint16_t drFreeBks; /* number of unused allocation blocks */
uint8_t drVN[kHFSMaxVolumeNameChars + 1]; /* volume name */
uint32_t drVolBkUp; /* date and time of last backup */
uint16_t drVSeqNum; /* volume backup sequence number */
uint32_t drWrCnt; /* volume write count */
uint32_t drXTClpSiz; /* clump size for extents overflow file */
uint32_t drCTClpSiz; /* clump size for catalog file */
uint16_t drNmRtDirs; /* number of directories in root folder */
uint32_t drFilCnt; /* number of files in volume */
uint32_t drDirCnt; /* number of directories in volume */
uint32_t drFndrInfo[8]; /* information used by the Finder */
uint16_t drEmbedSigWord; /* embedded volume signature (formerly drVCSize) */
HFSExtentDescriptor drEmbedExtent; /* embedded volume location and size (formerly drVBMCSize and drCtlCSize) */
uint32_t drXTFlSize; /* size of extents overflow file */
HFSExtentRecord drXTExtRec; /* extent record for extents overflow file */
uint32_t drCTFlSize; /* size of catalog file */
HFSExtentRecord drCTExtRec; /* extent record for catalog file */
} __attribute__((aligned(2), packed));
typedef struct HFSMasterDirectoryBlock HFSMasterDirectoryBlock;
#ifdef __APPLE_API_UNSTABLE
#define SET_HFS_TEXT_ENCODING(hint) \
(0x656e6300 | ((hint) & 0xff))
#define GET_HFS_TEXT_ENCODING(hint) \
(((hint) & 0xffffff00) == 0x656e6300 ? (hint) & 0x000000ff : 0xffffffffU)
#endif /* __APPLE_API_UNSTABLE */
/* HFS Plus Volume Header - 512 bytes */
/* Stored at sector #2 (3rd sector) and second-to-last sector. */
struct HFSPlusVolumeHeader {
uint16_t signature; /* == kHFSPlusSigWord */
uint16_t version; /* == kHFSPlusVersion */
uint32_t attributes; /* volume attributes */
uint32_t lastMountedVersion; /* implementation version which last mounted volume */
uint32_t journalInfoBlock; /* block addr of journal info (if volume is journaled, zero otherwise) */
uint32_t createDate; /* date and time of volume creation */
uint32_t modifyDate; /* date and time of last modification */
uint32_t backupDate; /* date and time of last backup */
uint32_t checkedDate; /* date and time of last disk check */
uint32_t fileCount; /* number of files in volume */
uint32_t folderCount; /* number of directories in volume */
uint32_t blockSize; /* size (in bytes) of allocation blocks */
uint32_t totalBlocks; /* number of allocation blocks in volume (includes this header and VBM*/
uint32_t freeBlocks; /* number of unused allocation blocks */
uint32_t nextAllocation; /* start of next allocation search */
uint32_t rsrcClumpSize; /* default resource fork clump size */
uint32_t dataClumpSize; /* default data fork clump size */
uint32_t nextCatalogID; /* next unused catalog node ID */
uint32_t writeCount; /* volume write count */
uint64_t encodingsBitmap; /* which encodings have been use on this volume */
uint8_t finderInfo[32]; /* information used by the Finder */
HFSPlusForkData allocationFile; /* allocation bitmap file */
HFSPlusForkData extentsFile; /* extents B-tree file */
HFSPlusForkData catalogFile; /* catalog B-tree file */
HFSPlusForkData attributesFile; /* extended attributes B-tree file */
HFSPlusForkData startupFile; /* boot file (secondary loader) */
} __attribute__((aligned(2), packed));
typedef struct HFSPlusVolumeHeader HFSPlusVolumeHeader;
/* B-tree structures */
enum BTreeKeyLimits{
kMaxKeyLength = 520
};
union BTreeKey{
uint8_t length8;
uint16_t length16;
uint8_t rawData [kMaxKeyLength+2];
};
typedef union BTreeKey BTreeKey;
/* BTNodeDescriptor -- Every B-tree node starts with these fields. */
struct BTNodeDescriptor {
uint32_t fLink; /* next node at this level*/
uint32_t bLink; /* previous node at this level*/
int8_t kind; /* kind of node (leaf, index, header, map)*/
uint8_t height; /* zero for header, map; child is one more than parent*/
uint16_t numRecords; /* number of records in this node*/
uint16_t reserved; /* reserved - initialized as zero */
} __attribute__((aligned(2), packed));
typedef struct BTNodeDescriptor BTNodeDescriptor;
/* Constants for BTNodeDescriptor kind */
enum {
kBTLeafNode = -1,
kBTIndexNode = 0,
kBTHeaderNode = 1,
kBTMapNode = 2
};
/* BTHeaderRec -- The first record of a B-tree header node */
struct BTHeaderRec {
uint16_t treeDepth; /* maximum height (usually leaf nodes) */
uint32_t rootNode; /* node number of root node */
uint32_t leafRecords; /* number of leaf records in all leaf nodes */
uint32_t firstLeafNode; /* node number of first leaf node */
uint32_t lastLeafNode; /* node number of last leaf node */
uint16_t nodeSize; /* size of a node, in bytes */
uint16_t maxKeyLength; /* reserved */
uint32_t totalNodes; /* total number of nodes in tree */
uint32_t freeNodes; /* number of unused (free) nodes in tree */
uint16_t reserved1; /* unused */
uint32_t clumpSize; /* reserved */
uint8_t btreeType; /* reserved */
uint8_t keyCompareType; /* Key string Comparison Type */
uint32_t attributes; /* persistent attributes about the tree */
uint32_t reserved3[16]; /* reserved */
} __attribute__((aligned(2), packed));
typedef struct BTHeaderRec BTHeaderRec;
/* Constants for BTHeaderRec attributes */
enum {
kBTBadCloseMask = 0x00000001, /* reserved */
kBTBigKeysMask = 0x00000002, /* key length field is 16 bits */
kBTVariableIndexKeysMask = 0x00000004 /* keys in index nodes are variable length */
};
/* Catalog Key Name Comparison Type */
enum {
kHFSCaseFolding = 0xCF, /* case folding (case-insensitive) */
kHFSBinaryCompare = 0xBC /* binary compare (case-sensitive) */
};
/* JournalInfoBlock - Structure that describes where our journal lives */
struct JournalInfoBlock {
uint32_t flags;
uint32_t device_signature[8]; // signature used to locate our device.
uint64_t offset; // byte offset to the journal on the device
uint64_t size; // size in bytes of the journal
uint32_t reserved[32];
} __attribute__((aligned(2), packed));
typedef struct JournalInfoBlock JournalInfoBlock;
enum {
kJIJournalInFSMask = 0x00000001,
kJIJournalOnOtherDeviceMask = 0x00000002,
kJIJournalNeedInitMask = 0x00000004
};
#ifdef __cplusplus
}
#endif
#endif /* __HFS_FORMAT__ */
+385
View File
@@ -0,0 +1,385 @@
/* Copyright 2007-2011 Apple Inc. All rights Reserved */
/* Copyright 2006 Apple Computer Inc, All Rights Reserved */
/*
* Interface shim between the iBoot fs/bdev layers and the HFS code.
*/
#include <debug.h>
#include <stdlib.h>
#include <string.h>
#include <lib/libc.h>
#include <lib/fs.h>
#include <lib/blockdev.h>
#ifndef HFS_UNITTEST
#include <sys/task.h>
#endif
#include "hfs.h"
#include "hfs_format.h"
#if 0
# define HFSdebug(fmt, args...) printf("%s: " fmt "\n", __FUNCTION__ , ##args)
#else
# define HFSdebug(fmt, args...) do { } while (0)
#endif
/*******************************************************************************
* fs interface
*/
static int hfs_mount(void **ctxt, const char *devname);
static void hfs_unmount(void *ctxt);
static int hfs_fsstat(void *ctxt, struct statfs *stat);
static void *hfs_open(void *ctxt, const char *path, uint8_t flags);
static int hfs_read(void *filectxt, void *buf, size_t len);
static int hfs_fstat(void *filectxt, struct stat *st);
static off_t hfs_seek(void *filectxt, off_t offset, int whence);
static void hfs_close(void *filectxt);
static void *hfs_opendir(void *ctxt, const char *path);
static int hfs_readdir(void *dirctxt, struct dirent *ent);
static void hfs_rewinddir(void *dirctxt);
static void hfs_closedir(void *dirctxt);
struct fs_ops hfs_fs_ops = {
hfs_mount,
hfs_unmount,
hfs_fsstat,
hfs_open,
hfs_read,
hfs_fstat,
hfs_seek,
hfs_close,
hfs_opendir,
hfs_readdir,
hfs_rewinddir,
hfs_closedir
};
struct hfs_context {
struct blockdev *dev;
struct statfs s;
uint32_t blocksize;
};
struct hfs_openfile {
struct hfs_context *fs;
char *path;
off_t pos;
struct stat s;
};
struct hfs_opendir {
struct hfs_context *fs;
char *path;
off_t pos;
};
/*
* Locking. Since the HFS code is not re-entrant, we must ensure
* that only one task calls into it at a time.
*/
#ifndef HFS_UNITTEST
static struct task *hfs_owner_task;
#define LOCK() \
do { \
while (hfs_owner_task != NULL) \
task_yield(); \
hfs_owner_task = current_task; \
} while(0);
#define UNLOCK() \
do { \
hfs_owner_task = NULL; \
} while(0);
#else
#define LOCK() do {} while(0)
#define UNLOCK() do {} while(0)
#endif
static int
hfs_mount(void **ctxt, const char *devname)
{
struct hfs_context *cp;
struct HFSPlusVolumeHeader *vh;
int result;
HFSdebug("mounting '%s'", devname);
result = -1;
LOCK();
cp = malloc(sizeof(struct hfs_context));
// find the device
if ((cp->dev = lookup_blockdev(devname)) == NULL)
goto out;
// make sure it's something we recognise
if (HFSInitPartition(cp))
goto out;
// HFSDetect();
// save FS stat info while we're at it
vh = HFSGetVolumeHeader();
cp->s.f_bsize = vh->blockSize;
cp->s.f_blocks = vh->totalBlocks;
cp->s.f_bfree = vh->freeBlocks;
result = 0;
out:
if (result) {
free(cp);
HFSdebug("mount failed");
} else {
HFSdebug("mounted fs %p", cp);
*ctxt = cp;
}
UNLOCK();
return(result);
}
static void
hfs_unmount(void *ctxt)
{
free(ctxt);
}
static int
hfs_fsstat(void *ctxt, struct statfs *stat)
{
struct hfs_context *cp = (struct hfs_context *)ctxt;
*stat = cp->s;
return(0);
}
static void *
hfs_open(void *ctxt, const char *path, uint8_t open_flags)
{
struct hfs_context *cp = (struct hfs_context *)ctxt;
struct hfs_openfile *of;
uint32_t flags;
uint32_t path_length;
time_t time;
off_t size;
HFSdebug("%s: openfile", path);
if (path[0] == '/')
path++;
of = NULL;
LOCK();
// check for file existence
if (HFSGetFileInfo(cp, path, &flags, &time, &size))
goto out;
if ((flags & kFileTypeMask) != kFileTypeFlat)
goto out;
// alloc file and populate path
path_length = strlen(path) + 1;
of = malloc(sizeof(struct hfs_openfile) + path_length);
of->path = (char *)(of + 1);
strlcpy(of->path, path, path_length);
of->pos = 0;
of->fs = cp;
// Since we have stat information courtesy of checking the file's existence,
// save it away for the inevitable stat.
of->s.st_ino = 0; // XXX
of->s.st_size = size;
of->s.st_blocks = size / cp->s.f_bsize + ((size % cp->s.f_bsize) ? 1 : 0);
of->s.st_type = FILE_TYPE_FILE;
of->s.st_flags = 0; // XXX
of->s.st_ctime = of->s.st_mtime = of->s.st_atime = time;
out:
UNLOCK();
if (of == NULL)
HFSdebug("openfile failed");
return(of);
}
static int
hfs_read(void *filectxt, void *buf, size_t len)
{
struct hfs_openfile *of = (struct hfs_openfile *)filectxt;
int result;
if (of->s.st_type != FILE_TYPE_FILE)
return(-1);
HFSdebug("%s: read %zu bytes to %p", of->path, len, buf);
result = HFSReadFile(of->fs, of->path, buf, of->pos, len);
if (result)
HFSdebug("read returns %d", result);
if (result > 0)
of->pos += result;
return(result);
}
static int
hfs_fstat(void *filectxt, struct stat *st)
{
struct hfs_openfile *of = (struct hfs_openfile *)filectxt;
*st = of->s;
return(0);
}
static off_t
hfs_seek(void *filectxt, off_t offset, int whence)
{
struct hfs_openfile *of = (struct hfs_openfile *)filectxt;
off_t newpos;
switch(whence) {
case FILE_SEEK_SET:
newpos = offset;
break;
case FILE_SEEK_CUR:
newpos = of->pos + offset;
break;
case FILE_SEEK_END:
newpos = of->s.st_size + offset;
break;
default:
return(-1);
}
if ((newpos < 0) || (newpos > of->s.st_size))
return(-1);
HFSdebug("%s: seek to 0x%llx", of->path, newpos);
return((of->pos = newpos));
}
static void
hfs_close(void *filectxt)
{
free(filectxt);
}
static void *
hfs_opendir(void *ctxt, const char *path)
{
struct hfs_context *cp = (struct hfs_context *)ctxt;
struct hfs_opendir *od;
uint32_t flags;
uint32_t path_length;
HFSdebug("%s: opendir", path);
od = NULL;
if (path[0] == '/')
path++;
LOCK();
// check for directory existence (/ always exists)
if (path[0] != '\0') {
if (HFSGetFileInfo(cp, path, &flags, 0, 0)) {
HFSdebug("%s: can't get directory info", path);
goto out;
}
}
// alloc file and populate path
path_length = strlen(path) + 1;
od = malloc(sizeof(struct hfs_opendir) + path_length);
od->path = (char *)(od + 1);
strlcpy(od->path, path, path_length);
od->pos = 0;
od->fs = cp;
out:
UNLOCK();
if (od == NULL) {
HFSdebug("opendir failed");
} else {
HFSdebug("opendir OK");
}
return(od);
}
static int
hfs_readdir(void *dirctxt, struct dirent *ent)
{
struct hfs_opendir *od = (struct hfs_opendir *)dirctxt;
uint32_t flags;
time_t time;
off_t size;
int result;
if (od->pos == -1)
return(-1); // end of directory
HFSdebug("%s: readdir at 0x%llx", od->path, od->pos);
LOCK();
if (HFSGetDirEntry(od->fs, od->path, &od->pos, ent->d_name, sizeof(ent->d_name), &flags, &time, &size) >= 0) {
ent->d_fileno = od->pos; // kinda dubious
RELEASE_ASSERT(size <= INT32_MAX);
ent->d_reclen = size; // ?! seems to be what it's for
switch(flags & kFileTypeMask) {
case kFileTypeFlat:
ent->d_type = FILE_TYPE_FILE;
break;
case kFileTypeDirectory:
ent->d_type = FILE_TYPE_DIR;
break;
default:
ent->d_type = FILE_TYPE_UNKNOWN;
break;
}
ent->d_name[sizeof(ent->d_name) - 1] = '\0';
ent->d_namlen = strlen(ent->d_name);
ent->d_ctime = ent->d_atime = ent->d_atime = time;
result = 0;
} else {
result = -1;
}
UNLOCK();
return(result);
}
static void
hfs_rewinddir(void *dirctxt)
{
struct hfs_opendir *od = (struct hfs_opendir *)dirctxt;
od->pos = 0;
}
static void
hfs_closedir(void *dirctxt)
{
free(dirctxt);
}
/*******************************************************************************
* bdev interface
*
* Note that the blockdev layer deblocks for us, so this interface is trivial.
*/
int
HFSBlockRead(CICell *ih, void *buf, off_t offset, uint32_t length)
{
struct hfs_context *cp = (struct hfs_context *)ih;
HFSdebug("HFS physical read from 0x%llx/0x%x to %p", (unsigned long long)offset, length, buf);
return(blockdev_read(cp->dev, buf, offset, length));
}
+32
View File
@@ -0,0 +1,32 @@
# Copyright (C) 2014 Apple Inc. All rights reserved.
#
# This document is the property of Apple Inc.
# It is considered confidential and proprietary.
#
# This document may not be reproduced or transmitted in any form,
# in whole or in part, without the express written permission of
# Apple Inc.
#
LIBHFS_DIR := $(GET_LOCAL_DIR)
LIBHFS_BUILD := $(call TOLIBDIR,$(LIBHFS_DIR)/LIBHFS.a)
COMMONLIBS += LIBHFS
# Only process the remainder of the makefile if we are building libraries
#
ifeq ($(MAKEPHASE),libraries)
GLOBAL_INCLUDES += $(SRCROOT)/arch/arm/include
LIBHFS_OBJS := \
$(LIBHFS_DIR)/cache.o \
$(LIBHFS_DIR)/hfs.o \
$(LIBHFS_DIR)/hfs_fs.o
LIBHFS_OBJS := $(call TOLIBOBJDIR,$(LIBHFS_OBJS))
ALL_DEPS += $(LIBHFS_OBJS:%o=%d)
$(LIBHFS_BUILD): $(LIBHFS_OBJS)
endif
+16
View File
@@ -0,0 +1,16 @@
# Copyright (C) 2008, 2014 Apple Inc. All rights reserved.
# Copyright (C) 2006 Apple Computer, Inc. All rights reserved.
#
# This document is the property of Apple Inc.
# It is considered confidential and proprietary.
#
# This document may not be reproduced or transmitted in any form,
# in whole or in part, without the express written permission of
# Apple Inc.
#
OPTIONS += WITH_HFS=1
MODULES += lib/fs
LIBRARY_MODULES += lib/fs \
lib/fs/hfs
+31
View File
@@ -0,0 +1,31 @@
#!/bin/bash
# Return an error if any commands below fail
set -e
echo "Creating test filesystem"
HFS_TEMPDIR=$(mktemp -d -t hfstest)
TESTFS_ROOT=${HFS_TEMPDIR}/testfs_root
export TESTFS_COMPARE_ROOT=${HFS_TEMPDIR}/testfs_compare
export TESTFS_IMAGE=${HFS_TEMPDIR}/testfs.dmg
DATA_PATTERN=evYya7KUSI1y5Tc05IQftxDuoIz8SlIRHDQLTA
mkdir $TESTFS_ROOT
for i in a a/a bb bb/bb-a bb/bb-b ccc dddd eeeee ffffff ggggggg hhhhhhhh iiiiiiiii jjjjjjjjjj kkkkkkkkkkk lllllllllllllllllllllllllllllllllllll m n o p q dir; do mkdir -p ${TESTFS_ROOT}/$i; done
dd if=/dev/zero of=${TESTFS_ROOT}/dir/testfile0 bs=1 count=0
dd if=/dev/zero of=${TESTFS_ROOT}/dir/testfile1 bs=1 count=1
dd if=/dev/zero of=${TESTFS_ROOT}/dir/testfile2 bs=1 count=2
dd if=/dev/zero of=${TESTFS_ROOT}/dir/testfile512 bs=1 count=512
dd if=/dev/zero of=${TESTFS_ROOT}/dir/testfile1024 bs=1 count=1024
for i in {1..1024}; do echo ${DATA_PATTERN} >> ${TESTFS_ROOT}/dir/testfile-${DATA_PATTERN}; done
echo "Creating disk image for test filesystem"
hdiutil create -size 4m -srcfolder $TESTFS_ROOT -format UDRW -fs HFSX -layout NONE $TESTFS_IMAGE
./fs
+30
View File
@@ -0,0 +1,30 @@
# Copyright (C) 2014 Apple Inc. All rights reserved.
#
# This document is the property of Apple Inc.
# It is considered confidential and proprietary.
#
# This document may not be reproduced or transmitted in any form,
# in whole or in part, without the express written permission of
# Apple Inc.
#
LOCAL_DIR := $(GET_LOCAL_DIR)
TEST_OBJS := \
lib/libc/log2.o \
lib/blockdev/blockdev.o \
lib/blockdev/mem_blockdev.o \
lib/fs/fs.o \
lib/fs/debug.o \
lib/fs/hfs/cache.o \
lib/fs/hfs/hfs.o \
lib/fs/hfs/hfs_fs.o
TEST_SUPPORT_OBJS := \
lib/env/env.o \
tests/mocks/blockdev.o \
tests/mocks/sys/security.o
TEST_CFLAGS := \
-DCPU_CACHELINE_SIZE=32 \
-DHFS_UNITTEST=1
+24
View File
@@ -0,0 +1,24 @@
# Copyright (C) 2014 Apple Inc. All rights reserved.
#
# This document is the property of Apple Inc.
# It is considered confidential and proprietary.
#
# This document may not be reproduced or transmitted in any form,
# in whole or in part, without the express written permission of
# Apple Inc.
#
LOCAL_DIR := $(GET_LOCAL_DIR)
TEST_NAME := fs-fuzz
include $(LOCAL_DIR)/tests-common.mk
TEST_SUPPORT_OBJS += \
tests/fuzz-main.o \
$(LOCAL_DIR)/fuzz.o
TEST_CFLAGS += \
-DNO_MOCK_ASSERTS=1
TEST_BUILD_ONLY := YES
+180
View File
@@ -0,0 +1,180 @@
#include <stdint.h>
#include <unittest.h>
#include <lib/blockdev.h>
#include <lib/fs.h>
#include <stdlib.h>
#include <string.h>
struct blockdev *create_mock_blockdev(const char *name, const char *filename, uint32_t block_size);
void test_fs(uintptr_t context) {
struct blockdev *bdev;
int result;
int handle;
void *buffer;
size_t load_size;
size_t buf_size;
const char *filename = getenv("TESTFS_IMAGE");
TEST_ASSERT_NOT_NULL(filename);
bdev = create_mock_blockdev("dev", filename, 4096);
register_blockdev(bdev);
result = fs_mount("dev", "hfs", "/boot");
TEST_ASSERT_EQ(result, 0);
fs_dump_dir("/boot", true);
fs_dump_dir("/boot/dir", true);
// Opening a non-existant path should fail
handle = fs_opendir("/boot/fake");
TEST_ASSERT_LT(handle, 0);
TEST_ASSERT_GTE((handle = fs_opendir("/boot")), 0);
TEST_ASSERT_EQ(fs_closedir(handle), 0);
TEST_ASSERT_GTE((handle = fs_opendir("/boot/a")), 0);
TEST_ASSERT_EQ(fs_closedir(handle), 0);
TEST_ASSERT_GTE((handle = fs_opendir("/boot/a/a")), 0);
TEST_ASSERT_EQ(fs_closedir(handle), 0);
TEST_ASSERT_GTE((handle = fs_opendir("/boot/bb")), 0);
TEST_ASSERT_EQ(fs_closedir(handle), 0);
TEST_ASSERT_GTE((handle = fs_opendir("/boot/bb/bb-a")), 0);
TEST_ASSERT_EQ(fs_closedir(handle), 0);
TEST_ASSERT_GTE((handle = fs_opendir("/boot/bb/bb-b")), 0);
TEST_ASSERT_EQ(fs_closedir(handle), 0);
TEST_ASSERT_GTE((handle = fs_opendir("/boot/ccc")), 0);
TEST_ASSERT_EQ(fs_closedir(handle), 0);
TEST_ASSERT_GTE((handle = fs_opendir("/boot/dddd")), 0);
TEST_ASSERT_EQ(fs_closedir(handle), 0);
TEST_ASSERT_GTE((handle = fs_opendir("/boot/eeeee")), 0);
TEST_ASSERT_EQ(fs_closedir(handle), 0);
TEST_ASSERT_GTE((handle = fs_opendir("/boot/ffffff")), 0);
TEST_ASSERT_EQ(fs_closedir(handle), 0);
TEST_ASSERT_GTE((handle = fs_opendir("/boot/ggggggg")), 0);
TEST_ASSERT_EQ(fs_closedir(handle), 0);
TEST_ASSERT_GTE((handle = fs_opendir("/boot/hhhhhhhh")), 0);
TEST_ASSERT_EQ(fs_closedir(handle), 0);
TEST_ASSERT_GTE((handle = fs_opendir("/boot/iiiiiiiii")), 0);
TEST_ASSERT_EQ(fs_closedir(handle), 0);
TEST_ASSERT_GTE((handle = fs_opendir("/boot/jjjjjjjjjj")), 0);
TEST_ASSERT_EQ(fs_closedir(handle), 0);
TEST_ASSERT_GTE((handle = fs_opendir("/boot/kkkkkkkkkkk")), 0);
TEST_ASSERT_EQ(fs_closedir(handle), 0);
TEST_ASSERT_GTE((handle = fs_opendir("/boot/lllllllllllllllllllllllllllllllllllll")), 0);
TEST_ASSERT_EQ(fs_closedir(handle), 0);
TEST_ASSERT_GTE((handle = fs_opendir("/boot/m")), 0);
TEST_ASSERT_EQ(fs_closedir(handle), 0);
TEST_ASSERT_GTE((handle = fs_opendir("/boot/n")), 0);
TEST_ASSERT_EQ(fs_closedir(handle), 0);
TEST_ASSERT_GTE((handle = fs_opendir("/boot/o")), 0);
TEST_ASSERT_EQ(fs_closedir(handle), 0);
TEST_ASSERT_GTE((handle = fs_opendir("/boot/p")), 0);
TEST_ASSERT_EQ(fs_closedir(handle), 0);
TEST_ASSERT_GTE((handle = fs_opendir("/boot/q")), 0);
TEST_ASSERT_EQ(fs_closedir(handle), 0);
TEST_ASSERT_GTE((handle = fs_opendir("/boot/dir")), 0);
TEST_ASSERT_EQ(fs_closedir(handle), 0);
buf_size = 1024 * 1024;
buffer = malloc(buf_size);
// Loading non-existant file should fail
load_size = buf_size;
result = fs_load_file("/boot/testfile1", (addr_t)buffer, &load_size);
TEST_ASSERT_EQ(result, -1);
// Load a file with 1 byte of zeroes
load_size = buf_size;
result = fs_load_file("/boot/dir/testfile1", (addr_t)buffer, &load_size);
TEST_ASSERT_EQ(result, 0);
TEST_ASSERT_EQ(load_size, 1);
// Load a file with 2 bytes of zeroes
load_size = buf_size;
result = fs_load_file("/boot/dir/testfile2", (addr_t)buffer, &load_size);
TEST_ASSERT_EQ(result, 0);
TEST_ASSERT_EQ(load_size, 2);
// Load a file with 512 bytes of zeroes
load_size = buf_size;
result = fs_load_file("/boot/dir/testfile512", (addr_t)buffer, &load_size);
TEST_ASSERT_EQ(result, 0);
TEST_ASSERT_EQ(load_size, 512);
// Load a file with 1024 bytes of zeroes
load_size = buf_size;
result = fs_load_file("/boot/dir/testfile1024", (addr_t)buffer, &load_size);
TEST_ASSERT_EQ(result, 0);
TEST_ASSERT_EQ(load_size, 1024);
// Load a file with a repeating data pattern
const char *pattern = "evYya7KUSI1y5Tc05IQftxDuoIz8SlIRHDQLTA\n";
size_t pattern_len = strlen(pattern);
load_size = buf_size;
result = fs_load_file("/boot/dir/testfile-evYya7KUSI1y5Tc05IQftxDuoIz8SlIRHDQLTA", (addr_t)buffer, &load_size);
TEST_ASSERT_EQ(result, 0);
TEST_ASSERT_EQ(load_size, pattern_len * 1024);
char *current = buffer;
for (unsigned i = 0; i < 1024; i++) {
TEST_ASSERT_MEM_EQ(current, pattern, pattern_len);
current += pattern_len;
}
// Verify a non-existant file is not found in a directory that exists
load_size = buf_size;
result = fs_load_file("/boot/dir/non-existant", (addr_t)buffer, &load_size);
TEST_ASSERT_EQ(result, -1);
// Verify a existant file is not found in the wrong directory
load_size = buf_size;
result = fs_load_file("/boot/non-existant/testfile1", (addr_t)buffer, &load_size);
TEST_ASSERT_EQ(result, -1);
free(buffer);
}
struct test_suite fs_suite = {
.name = "fs",
.test_cases = {
{ "fs", test_fs, 0, "" },
TEST_CASE_LAST
}
};
TEST_SUITE(fs_suite);
// Mock
bool
env_blacklist(const char *name, bool write)
{
return false;
}
// Mock
bool
env_blacklist_nvram(const char *name)
{
return false;
}
+29
View File
@@ -0,0 +1,29 @@
# Copyright (C) 2014 Apple Inc. All rights reserved.
#
# This document is the property of Apple Inc.
# It is considered confidential and proprietary.
#
# This document may not be reproduced or transmitted in any form,
# in whole or in part, without the express written permission of
# Apple Inc.
#
LOCAL_DIR := $(GET_LOCAL_DIR)
TEST_NAME := fs
include $(LOCAL_DIR)/tests-common.mk
TEST_SUPPORT_OBJS += \
tests/unittest-main.o \
$(LOCAL_DIR)/tests.o
HELPER := test-hfs-helper.sh
HELPER_INSTALL := $(call TOTESTDIR,$(HELPER))
$(HELPER_INSTALL): $(LOCAL_DIR)/$(HELPER)
$(_v)cp $< $@
EXTRA_TEST_PRODUCTS += $(HELPER_INSTALL)
TEST_RUN_COMMAND := ./$(HELPER)